我想用javascript和html画布制作一个动画,只是让一个矩形从窗口顶部移动到底部,我用canvas.clearRect来清除画布上的所有像素,但是,似乎这个功能不起作用,之前的绘图仍然存在。这是所有代码
<!DOCTYPE HTML>
<html>
<title>Jave script tetris by zdd</title>
<head>
<script>
function point(x, y)
{
this.x = x;
this.y = y;
}
function draw(timeDelta)
{
// Vertices to draw a square
var v1 = new point( 0, 0);
var v2 = new point(100, 0);
var v3 = new point(100, 100);
var v4 = new point( 0, 100);
this.vertices = [v1, v2, v3, v4];
// Get canvas context
var c = document.getElementById("canvas");
var cxt = c.getContext("2d");
// Clear the canvas, this does not work?
cxt.clearRect(0, 0, 800, 600);
// Move the piece based on time elapsed, just simply increase the y-coordinate here
for (var i = 0; i < this.vertices.length; ++i)
{
this.vertices[i].y += timeDelta;
}
cxt.moveTo(this.vertices[0].x, this.vertices[0].y);
for (var i = 1; i < this.vertices.length; ++i)
{
cxt.lineTo(this.vertices[i].x, this.vertices[i].y);
}
cxt.lineTo(this.vertices[0].x, this.vertices[0].y);
cxt.stroke();
}
var lastTime = Date.now();
function mainLoop()
{
window.requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.requestAnimationFrame(mainLoop);
var currentTime = Date.now();
var timeDelta = (currentTime - lastTime);
draw(timeDelta);
lastTime = currentTime;
}
</script>
</head>
<body>
<canvas id="canvas" width="800" height="600">
</canvas>
<script>
</script>
<button type="button" style="position:absolute; left:500px; top:600px; width:100px; height:50px;" class="start" onclick="mainLoop()">start</button>
</body>
</html>
这里是Chrome中的结果图片,我只想要一个矩形,但clearRect函数没有清除旧矩形,所以......,如何解决这个问题?
答案 0 :(得分:2)
您缺少beginPath
。没有它,每个盒子实际上都是最后一个盒子的一部分。
cxt.beginPath();
cxt.moveTo(this.vertices[0].x, this.vertices[0].y);
for (var i = 1; i < this.vertices.length; ++i) {
cxt.lineTo(this.vertices[i].x, this.vertices[i].y);
}
添加之后,框似乎在四处摇晃,不确定这是不是你的意图。
这是一个小提琴:http://jsfiddle.net/6xbQN/
祝你好运!