奇怪的线条出现在画布上

时间:2017-09-15 02:51:05

标签: javascript html canvas

我正在尝试使用arc方法为我的画布中的曲线中出现的许多圆圈设置动画,并且出现一条奇怪的切线但不应该是这种情况,因为我没有包含任何代码来显示该行,仅适用于圈子。有人可以向我解释为什么会出现这条线?这是所有代码

window.requestAnimFrame = (function() {
       /* window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || */
  return function(callback) {
    window.setTimeout(callback, 1000);
  };
})();
var graph = {
  x: 0,
  y: 0,
  incur: 0.6,
  canvas: document.getElementsByTagName('canvas')[0],
  ctx: null,
  ratio: 640 / 1136,
  init: function() {
    graph.ctx = graph.canvas.getContext('2d');


    graph.resize();

  },
  resize: function() {
    graph.canvas.height = window.innerHeight;
    graph.canvas.width = graph.ratio * window.innerHeight;
    console.log("asd")


  },
  loop: function() {
    graph.incur += 0.6
    window.requestAnimFrame(graph.loop);
    console.log(graph.incur)
    graph.x += graph.incur
    graph.y += graph.incur * graph.incur

    //graph.draw.clear();
    graph.draw.circle(graph.x, graph.y, 10, "#FF0000")

  }


}
graph.draw = {
  clear: function() {
    graph.ctx.clearRect(0, 0, graph.canvas.width, graph.canvas.height)
  },

  circle: function(x, y, r, col) {
    graph.ctx.fillStyle = col;
    graph.ctx.arc(x, y, r, 0, Math.PI * 2, true)
    graph.ctx.fill();
  }



}
graph.init();
window.addEventListener("resize", graph.resize);
graph.loop();
canvas {
  display: block;
  margin: 0 auto;
  background-color: #808080;
}
<canvas>
</canvas>

这是一个链接到奇怪线的屏幕截图:

weird line

1 个答案:

答案 0 :(得分:1)

该行正在显示,因为arc方法会将路径移动到起始x / y坐标 - 通过这样做绘制一条线,然后绘制圆。您可以在绘制圆之前调用moveTo来轻松避免此行为。

演示:

&#13;
&#13;
window.requestAnimFrame = (function(){
 return function( callback ){
    window.setTimeout(callback, 1000);
  }
})()

var graph = {
    x: 0,
    y: 0,
    incur: 0.6,
    canvas: document.querySelector('canvas'),
    ctx: null,
    ratio: 640/1136,

    init(){
        graph.ctx = graph.canvas.getContext('2d');
        graph.resize();
    },

    resize(){
        graph.canvas.height = window.innerHeight;
        graph.canvas.width = graph.ratio * window.innerHeight;
    },

    loop(){
        graph.incur += 0.6
        window.requestAnimFrame(graph.loop)
        graph.x += graph.incur
        graph.y += graph.incur ** 2
        graph.draw.circle(graph.x,graph.y,10,"#FF0000")
    },

    draw: {
        circle(x, y, r, color) {
            graph.ctx.fillStyle = color
            graph.ctx.moveTo(x + arc.radius, y)
            graph.ctx.arc(x, y, r, 0, Math.PI * 2)
            graph.ctx.fill()
        }
    }
}

graph.init();
window.addEventListener("resize", graph.resize);
graph.loop();
&#13;
canvas {
  display: block;
  margin: 0 auto;
  background-color: #808080;
}
&#13;
<canvas></canvas>
&#13;
&#13;
&#13;