2017-03-08 118 views
0

我使用drawCircle函數在html5畫布上繪製圓圈(this.ctx)。現在我想通過移動Circle函數將cirlce移到不同的位置。有沒有辦法看到圈子從一個地方移動到另一個地方?在這一點上,我甚至不知道如何刪除用戶的以前的圈子。我可以將弧線分配給某個物體嗎?在html5畫布上移動圈圈

customobject.prototype.drawCircle = function drawCircle(userID, x, y) { 

var radius = 10; 
     this.ctx.beginPath(); 
     this.ctx.arc(100, 00, 10, 0, Math.PI*2, true); 
     this.ctx.closePath(); 
     this.ctx.fillStyle = 'blue'; 
     this.ctx.fill(); 
     this.ctx.lineWidth = 2; 
     this.ctx.strokeStyle = '#003300'; 
     this.ctx.stroke(); 
} 


customobject.prototype.moveCircle = function moveCircle(userID, x, y) { 

} 

我確實看到了一種可能刪除了一圈(不動畫 - 移動):

remove circle(x, y, radius){ 
    this.ctx.globalCompositeOperation = 'destination-out' 
    this.ctx.arc(x, y, radius, 0, Math.PI*2, true); 
    this.ctx.fill(); 
} 

- >所以在這種情況下,我會指定原始圓的座標,它會被切斷?

我也看到了做一個圓圈移動this後。但我不知道如何與多個圈子做到這一點。 (每個用戶ID都會有一個圓圈)

+0

如果你有多個圓圈,那麼最好的方法是使用像easel.js這樣的庫。好處是你可以給每個對象一個ID,並可以單獨對它們執行一些操作。當然,如果你使用自定義方法,那麼@ philipp是正確的,你必須清除畫布,並使用requestAnimationFrame()重繪所有內容。 –

+0

如果有多個圓圈,他也可以使用一個簡單的數組,如'[{start :, end :, p1:{},p1:{},...},{...},...]'。然後只是循環,並呈現每個。但如果你需要更多的形狀,樣式,緩動功能,比圖書館更好。 – philipp

回答

2

一旦繪製出一個圓圈後,從畫布上移除一個圓是事先不可能的,您可以在該位置繪製另一個圓,但是背景顏色設置爲,但會與其他圓形快速衝突繪製的對象。

如果我得到這個權利,你想動畫圓的運動。這基本上是做這樣的:

var start = new Date().getTime(), 
    end = start + 1000; //one second of animation 
    p1 = { x: 0, y: 0 }, //start coordinates 
    p2 = { x: 100, y: 10 }; // end coordinates 


function render (progress) { 
    var x = p1.x + progress * (p2.x - p1.x), 
     y = p1.y + progress * (p2.y - p1.y); 

    clearCanvas(); 
    drawCircle(x,y); 
} 

function loop() { 
    var now = new Date().getTime(), 
     progress = (now - start)/(end - start); 

    if (progress >= 0 && progress <= 1) { 
    render(progress); 
    window.requestAnimationFrame(loop); 
    } 
} 

loop(); 

基礎知識:

  1. 你需要一個動畫循環,沒有forwhile循環,一些使用一個計時器,setTimeout()setInterval()會做,但requestAnimationFrame()是爲了這樣的事情。

  2. 查找的進展,動畫這通常是在0和1之間的一個數,其中0表示開始,1到結束,一切都在進步之間。

  3. 清除畫布和重新渲染一切,取決於進展。

  4. 重複,直到進度比一個大。