我试图做到这一点,当用户点击屏幕上的任何地方时,点击的地方会出现一个圆圈,并继续扩大。如果可能的话,我不想使用 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();
}
}
}
我的错误似乎是,它没有显示圆圈在增长,而是显示了所有堆叠起来的圆圈。理想情况下,用户可以点击两三个地方并看到多个圈子在增长。任何帮助表示赞赏。谢谢。
最佳答案
您遇到的问题是代码在硬循环中调用自身 - 基本上只是用颜色淹没了背景。
尝试像这样在 setTimeout 中包装您的 function2 调用:
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);
关于javascript - HTML5 Canvas 成长圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292179/