Javascript 画布上下文的clearRect不清除像素
我想用javascript和html画布制作一个动画,只需将一个矩形从窗口顶部移动到底部,我使用canvas.clearRect来清除画布上的所有像素,但是,这个函数似乎不起作用,之前的绘图仍然存在。这是所有的代码Javascript 画布上下文的clearRect不清除像素,javascript,html,canvas,Javascript,Html,Canvas,我想用javascript和html画布制作一个动画,只需将一个矩形从窗口顶部移动到底部,我使用canvas.clearRect来清除画布上的所有像素,但是,这个函数似乎不起作用,之前的绘图仍然存在。这是所有的代码 <!DOCTYPE HTML> <html> <title>Jave script tetris by zdd</title> <head> <script>
<!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>
Jave脚本俄罗斯方块zdd
功能点(x,y)
{
这个.x=x;
这个。y=y;
}
函数绘制(时间增量)
{
//绘制正方形的顶点
var v1=新点(0,0);
var v2=新点(100,0);
var v3=新点(100100);
var v4=新点(0,100);
this.vertices=[v1,v2,v3,v4];
//获取画布上下文
var c=document.getElementById(“画布”);
var cxt=c.getContext(“2d”);
//清除画布,这不起作用?
cxt.clearRect(0,0,800,600);
//根据经过的时间移动工件,只需在此处增加y坐标
对于(var i=0;i
这是Chrome中的结果图片,我只想要一个矩形,但是clearRect函数没有清除旧的矩形,所以…,如何修复?
您缺少
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);
}
cxt.beginPath();
移动到(this.vertices[0].x,this.vertices[0].y);
对于(var i=1;i
加上这些之后,盒子似乎在晃动,不确定这是否是你的意图
这是一把小提琴:
祝你好运 因为您已经在调用“context.clearRect(0,0,canvas.width,canvas.height)”;-控制台中有错误吗?@nycyik,你看到我的代码了吗?我在draw函数中有它。那不是真的,它与beginPath无关。添加它后,我不再看到多个框。你试过了吗?为什么它不起作用?你能弄清楚它不起作用吗?你是说你还看到多个盒子?这是小提琴,你可以清楚地看到只有一个动画框。我想你还有一个与盒子的移动和时间差有关的问题。我仍然在我的电脑上看到多个盒子。