0
如果將鼠標懸停在網格上,正方形將變爲紅色。現在我想讓他們在1秒後使用淡出效果改回原來的顏色(黑色)。有人可以幫忙嗎?畫布恢復顏色
我已經嘗試了一些沿着ctx.restore的行,但我想我沒有正確實現它,因爲它什麼也沒做。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
\t \t overflow:hidden;
}
\t
\t #wrap {
\t \t width: 600px;
\t \t height: 600px;
\t }
</style>
</head>
<body bgcolor="#252525">
<div class="wrap"><canvas id="canvas" width="5000" height="3000"></canvas></div>
<script>
var ctx = canvas.getContext("2d"),
cw = 32,
ch = 32,
w = canvas.width,
h = canvas.height;
ctx.translate(0.5, 0.5);
ctx.beginPath();
for(var y = 0; y < h; y += ch) {
for(var x = 0; x < w; x += cw) {
ctx.rect(x, y, cw-2, ch-2); // give 1px space
}
}
ctx.fillStyle = "black";
ctx.strokeStyle = "#000";
ctx.lineWidth=1;
ctx.fill();
ctx.stroke();
canvas.onmousemove = function(e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
cx = ((x/cw)|0) * cw,
cy = ((y/ch)|0) * ch;
ctx.fillStyle = "red";
ctx.fillRect(cx+1, cy+1, cw-3, ch-3);
};
</script>
</body>
</html>
謝謝你的任何和所有的反饋!
您可以在您的fillRect使用超時https://developer.mozilla.org/en-US/ docs/Web/API/WindowTimers.setTimeout恢復爲舊顏色。 –
這樣的事情? http://jsbin.com/poqezohisi/1/edit?js,output – GameAlchemist
是的!非常感謝!你會碰巧知道如何隨機化「紅」色嗎?像獲得隨機顏色,紅色,藍色,綠色等,而不是隻有紅色。 –