2013-08-17 82 views
3

我试图让用户点击屏幕上的任何地方,点击时会出现一个圆圈,然后继续增长。如果可能,我不想使用jQuery。我做了一个的jsfiddle:http://jsfiddle.net/VZ8R4/HTML5 Canvas Growing Circles

我认为错误是在中国保监会()函数:

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

} 

我的错误似乎是,而不是显示的圆形成长,它只是显示所有的圆圈堆积起来。理想情况下,用户可以点击两三个地点,看到多个圈子正在增长。任何帮助表示赞赏。谢谢。

+0

你的小提琴我试图拉入资源无法加载。 – dc5

+0

?对不起,我不确定你的意思。 –

回答

2

您遇到的问题是代码在硬循环中调用自己 - 基本上只是用颜色填充背景。

尝试包裹在你的setTimeout调用函数2这样的:

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

Fiddle

你可能会想看看requestAnimationFrame,但这应该让你去。

此外,这只能得到扩大的圈子。根据您想要的最终效果,您可能需要跟踪已开始的圆,并在每个动画过程中迭代/绘制它们。

更新

继承人,做一个更好的工作画的圆圈相互重叠,并使用requestAnimationFrame(webkit的版本)

Demo

代码(只是相关部分)版本

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); 
+0

它不能像我想要的那样工作,但它足以让我到那里。谢谢! –

+0

@NoahT - 更新的答案与更多的版本,我*认为*更符合您的需求。 – dc5