【问题标题】:Why does canvas draw lines between circle (arc)?为什么画布在圆(弧)之间画线?
【发布时间】:2014-01-02 13:11:22
【问题描述】:

在画布的那一刻,画出 15 个从 ltr 移动的具有不同速度和大小的圆圈。当其中一个离开窗口时,它将被设置为开始。问题是画布在圆圈之间画线,我不知道为什么?有人可以帮忙吗?

window.onload = function () {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var W = canvas.width = window.innerWidth;
    var H = canvas.height = window.innerHeight;
    var mp = 15; //max particles
    var particles = [];
    //var rotate = 180;

    reqAnimFrame = window.requestAnimationFrame ||
                   window.mozRequestAnimationFrame    ||
                   window.webkitRequestAnimationFrame ||
                   window.msRequestAnimationFrame     ||
                   window.oRequestAnimationFrame;

    for ( var i = 0; i < mp; i++ )
        {
            particles.push({
                x: Math.floor(Math.random()*W), //x-coordinate
                y: Math.floor(Math.random()*H), //y-coordinate
                d: Math.floor(Math.random()*(mp - 1) + 1), //density
                r: Math.floor(Math.random()*(70 - 10) + 10) //radius
            })
        }



    function animate() {
        reqAnimFrame(animate);
        for ( var i = 0; i < mp; i++ )
            {
                var p = particles[i];
                p.x += p.d;


                if(p.x >= W){
                    p.x = -300;
                    p.y = Math.floor(Math.random()*H);
                }
                draw();
            }
    }

    function draw() {
        ctx.clearRect(0, 0, W, H);
        ctx.fillStyle = "rgba(0,204,142,1";
        ctx.beginPath();
        for ( var i = 0; i < mp; i++ )
            {
                var p = particles[i];
                ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, false);
                //ctx.moveTo(p.x,p.y);
                //ctx.lineTo(p.x + 150, p.y + (-180));
                //ctx.lineTo(p.x + 300, p.y);
            }
        ctx.stroke();
    }
    animate();
    };//onload function

【问题讨论】:

    标签: javascript html animation canvas


    【解决方案1】:

    稍微更改一下代码,因为 beginPath()stroke() 现在只调用一次 - 发生的情况是弧在循环中累积,因为它们不是真正的圆 - 它们有两个开放端 - 这些端将相互连接,在弧之间创建线。

    尝试以下方法:

    function draw() {
        ctx.clearRect(0, 0, W, H);
        ctx.fillStyle = "rgba(0,204,142,1";
        for ( var i = 0; i < mp; i++ ) {
            var p = particles[i];
            ctx.beginPath();
            ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, false);
            ctx.stroke();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多