gpt4 book ai didi

javascript - 如何将对象移动到一条线上并删除旧对象,这样它就不会在 HTML5 Canvas 中留下尾部?

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

我试图将一个球移到一条线上,但是当我改变位置时它会把旧物体留在线上。如何在 HTML5 中将对象平滑地移动到一条直线上?

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.beginPath();
context.moveTo(10, 10);
context.lineTo(400, 10);
context.stroke();


function clickToAddBall() {
// Do something
}

function gameLoop() {
var loop = 400;
setInterval(function() {
loop = loop - 10;
drawABall(loop);
}, 200);
}
gameLoop();

function drawABall(positionX) {

context.beginPath();
context.arc(positionX, 10, 5, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

}

http://jsfiddle.net/noppanit/z5VwL/2/

最佳答案

每次重绘都需要清空 Canvas 。我加了

context.clearRect(0,0,578, 200 );

绘制函数...

function drawABall(positionX) {
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 5;

context.clearRect(0,0,578, 200 );

context.beginPath();
context.arc(positionX, 10, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

}

举个简单的例子,这是一个 fiddle 。

http://jsfiddle.net/z5VwL/3/

关于javascript - 如何将对象移动到一条线上并删除旧对象,这样它就不会在 HTML5 Canvas 中留下尾部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22747269/

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