gpt4 book ai didi

javascript - Canvas 上下文的 clearRect 不清除像素

转载 作者:行者123 更新时间:2023-11-30 18:13:54 25 4
gpt4 key购买 nike

我想用 javascript 和 html canvas 制作一个动画,只是让一个矩形从窗口的顶部移动到底部,我使用 canvas.clearRect 清除 Canvas 上的所有像素,但是,看起来这个功能失效了,之前的图还在。这是所有的代码

<!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 函数没有清除旧矩形,所以...,如何解决这个问题? enter image description here

最佳答案

您缺少 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);
}

添加之后,盒子似乎在晃动,不确定这是否是您的意图。

这是一个 fiddle :http://jsfiddle.net/6xbQN/

祝你好运!

关于javascript - Canvas 上下文的 clearRect 不清除像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13842467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com