3

我正在努力做到这一点,当用户点击屏幕上的任意位置时,点击点会出现一个圆圈,并继续增长。如果可能的话,我不想使用 jQuery。我做了一个JSFiddle:http: //jsfiddle.net/VZ8R4/

我认为错误出在 circ() 函数中:

function circ(x, y, rad, c){    
    ctx.beginPath();
    ctx.arc(x, y, rad, 0, 2 * Math.PI, false);

    ctx.lineWidth = 5;
    ctx.strokeStyle = c;
    ctx.stroke();
    function2();
    function function2(){
        ctx.beginPath();
        ctx.arc(x, y, rad, 0, 2 * Math.PI, false);

        ctx.lineWidth = 5;
        ctx.strokeStyle = c;
        ctx.stroke();
        rad+=3;
        if(rad<=canvas.width){
            function2();
        }
    }

}

我的错误似乎是,它没有显示圆圈变大,而是显示所有圆圈堆叠在一起。理想情况下,用户可以点击两三个地方并看到多个圈子在增长。任何帮助表示赞赏。谢谢。

4

1 回答 1

2

你遇到的问题是代码在一个硬循环中调用自己 - 基本上只是用颜色淹没背景。

尝试将您的 function2 调用包装在 setTimeout 中,如下所示:

if (rad <= canvas.width) {
    setTimeout(function2, 200);
}

小提琴

您可能想看一下requestAnimationFrame,但这应该可以帮助您。

此外,这只会使圈子扩大。根据您想要的最终效果,您可能需要跟踪已开始的圆圈,并在每个动画传递期间迭代/绘制它们。

更新

这是一个更好地绘制相互重叠的圆圈并使用requestAnimationFrame(webkit版本)的版本

演示

代码 (只是相关部分)

var circles = [];

function circ(x, y, rad, c) {
    ctx.fillStyle = c;  // <<== Sets the fill color
    ctx.beginPath();
    ctx.arc(x, y, rad, 0, 2 * Math.PI, false);

    // No need to update context these as we are filling the circle instead
    //ctx.lineWidth = 5;
    //ctx.strokeStyle = c;
    //ctx.stroke();

    ctx.closePath();
    ctx.fill();  // <<== Fills the circle with fill color
}

function draw() {
    var newCircles = [];
    for (var i = 0; i < circles.length; ++i) {
        circ(circles[i].x, circles[i].y, circles[i].radius, circles[i].colour);
        circles[i].radius += 3;
        if (circles[i].radius <= canvas.width) newCircles.push(circles[i]);
    }

    circles = newCircles;
    window.webkitRequestAnimationFrame(draw);
}

window.webkitRequestAnimationFrame(draw);
于 2013-08-17T18:53:47.530 回答