2016-07-26 34 views
1

我正在學習JavaScript,所以我現在還是新手。我有一張我在HTML畫布中繪製的圖像。它們的大小相同,但爲了減少代碼,我想知道是否可以在var中轉換一個,然後調整第二個的位置?JavaScript - 一個變種3的形狀

繼承人我的代碼:

   // Cloud 1 
       ctx.beginPath(); 
       ctx.fillStyle = "#fff"; 
       ctx.ellipse(320, 170, 38, 25, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(340, 156, 32, 35, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(368, 174, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(390, 174, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(392, 173, 30, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.fill(); 

       // Cloud 2 
       ctx.beginPath(); 
       ctx.fillStyle = "#fff"; 
       ctx.ellipse(720, 100, 38, 25, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(740, 86, 32, 35, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(768, 104, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(790, 104, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.ellipse(792, 103, 30, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
       ctx.fill(); 
+0

好的,也許我沒有解釋我希望做什麼。基本上,我試圖把雲1變成一個變種,所以如果需要的話,我可以把它放在別的地方多次。現在我不知道這是否可能。我從來沒有在其中看到過形狀代碼的變種。 –

+0

看到我的答案。你可以將你的cloud1繪圖代碼放入一個函數中(所以你不需要重複它),然後使用'context.translate(offsetX,offsetY)'在畫布上的任意位置重新定位多個cloud1。 – markE

回答

1
var clouds = []; 

clouds.push({x: 320, y: 170}); 

clouds.push({x: 324, y: 156}); 

.... 

.... 


for (cloud = 0; cloud <10; cloud++){ 
    ctx.ellipse(clouds[cloud].x, clouds[cloud].y, 30, 26, 0 * Math.PI/180, 0, 2 * Math.PI); 
} 
1

你可以在畫布的當前圖像數據,並把它背在不同的地方:

var data = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); 
ctx.putImageData(data, deltaX, deltaY); 

凡DELTAX和移動deltaY是你要多少水平和垂直移動圖像。

在你的情況下,deltaX是400,deltaY是-70。

相關問題