在html5画布上移动圈圈
问题描述:
我使用drawCircle函数在html5画布上绘制圆圈(this.ctx)。现在我想通过移动Circle函数将cirlce移到不同的位置。有没有办法看到圈子从一个地方移动到另一个地方?在这一点上,我甚至不知道如何删除用户的以前的圈子。我可以将弧线分配给某个物体吗?在html5画布上移动圈圈
customobject.prototype.drawCircle = function drawCircle(userID, x, y) {
var radius = 10;
this.ctx.beginPath();
this.ctx.arc(100, 00, 10, 0, Math.PI*2, true);
this.ctx.closePath();
this.ctx.fillStyle = 'blue';
this.ctx.fill();
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = '#003300';
this.ctx.stroke();
}
customobject.prototype.moveCircle = function moveCircle(userID, x, y) {
}
我确实看到了一种可能删除了一圈(不动画 - 移动):
remove circle(x, y, radius){
this.ctx.globalCompositeOperation = 'destination-out'
this.ctx.arc(x, y, radius, 0, Math.PI*2, true);
this.ctx.fill();
}
- >所以在这种情况下,我会指定原始圆的坐标,它会被切断?
我也看到了做一个圆圈移动this后。但我不知道如何与多个圈子做到这一点。 (每个用户ID都会有一个圆圈)
答
一旦绘制出一个圆圈后,从画布上移除一个圆是事先不可能的,您可以在该位置绘制另一个圆,但是背景颜色设置为,但会与其他圆形快速冲突绘制的对象。
如果我得到这个权利,你想动画圆的运动。这基本上是做这样的:
var start = new Date().getTime(),
end = start + 1000; //one second of animation
p1 = { x: 0, y: 0 }, //start coordinates
p2 = { x: 100, y: 10 }; // end coordinates
function render (progress) {
var x = p1.x + progress * (p2.x - p1.x),
y = p1.y + progress * (p2.y - p1.y);
clearCanvas();
drawCircle(x,y);
}
function loop() {
var now = new Date().getTime(),
progress = (now - start)/(end - start);
if (progress >= 0 && progress <= 1) {
render(progress);
window.requestAnimationFrame(loop);
}
}
loop();
基础知识:
你需要一个动画循环,没有
for
或while
循环,一些使用一个计时器,setTimeout()
或setInterval()
会做,但requestAnimationFrame()
是为了这样的事情。查找的进展,动画这通常是在0和1之间的一个数,其中0表示开始,1到结束,一切都在进步之间。
清除画布和重新渲染一切,取决于进展。
重复,直到进度比一个大。
如果你有多个圆圈,那么最好的方法是使用像easel.js这样的库。好处是你可以给每个对象一个ID,并可以单独对它们执行一些操作。当然,如果你使用自定义方法,那么@ philipp是正确的,你必须清除画布,并使用requestAnimationFrame()重绘所有内容。 –
如果有多个圆圈,他也可以使用一个简单的数组,如'[{start :, end :, p1:{},p1:{},...},{...},...]'。然后只是循环,并呈现每个。但如果你需要更多的形状,样式,缓动功能,比图书馆更好。 – philipp