[英]HTML5 Canvas Growing Circles
我試圖這樣做,當用戶點擊屏幕上的任何地方時,點擊時會出現一個圓圈,然后繼續增長。 如果可能的話,我不想使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.