【问题标题】:Moving circles on html5 canvas在 html5 画布上移动圆圈
【发布时间】:2017-03-08 17:53:48
【问题描述】:

我正在使用 drawCircle 函数在 html5 画布 (this.ctx) 上绘制圆圈。现在我想用移动圆圈功能将圆圈移动到不同的位置。有没有办法看到圆圈从一个地方移动到另一个地方?在这一点上,我什至不确定如何为用户删除前一个圈子。我可以将弧分配给一个对象吗?

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 都会有一个圆圈)

【问题讨论】:

  • 如果你有多个圈子,那么最好的方法是使用像easel.js这样的库。好处是您将能够给每个对象一个 ID,并可以单独对它们执行一些操作。当然,如果您使用自定义方法,那么@philipp 是正确的,您必须清除画布并使用 requestAnimationFrame() 重绘所有内容。
  • 如果有多个圈子,他也可以使用像[{start:, end:, p1:{}, p1:{}, …}, {…}, …] 这样的简单数组。然后只是循环并渲染每个。但是如果你需要更多的形状、样式、缓动函数,那么库会更好。

标签: javascript html


【解决方案1】:

从画布中删除一个圆形是不可能的,您可以在该位置绘制另一个圆形,但设置了背景颜色,但这会很快与其他绘制的对象发生冲突。

如果我做对了,您希望为圆的运动设置动画。基本上就是这样完成的:

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();

基础知识:

  1. 你需要一个动画循环,而不是 forwhile 循环,使用计时器的东西,setTimeout()setInterval() 可以,但 requestAnimationFrame() 是为这样的事情而设计的。

  2. 查找进度,在动画中这通常是一个介于 0 和 1 之间的数字,其中 0 表示开始,1 表示结束以及进度之间的所有内容。

  3. 根据进度清除画布并重新渲染所有内容。

  4. 重复直到进度大于一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2011-07-25
    • 1970-01-01
    相关资源
    最近更新 更多