2015-10-07 16 views
3
困惑

我想編程像這樣一個謝爾賓斯基地毯的前幾個迭代的一個簡單的演示:通過globalCompositeOperation

Sierpinski Carpet

我要繼續的方式是通過點擊應用基本格局面具在較小的範圍內每一步。在我看來,通過從黑色方塊開始,然後使用「目標進入」的globalCompositeOperation和源代碼遮罩,就像第二個圖像一樣,我應該能夠做到我想要的,但我努力要把它一起。

這繪製背景上的黑色正方形:

context.globalCompositeOperation = "source-over"; 
context.fillStyle = 'black'; 
context.fillRect(0, 0, 500, 500); 

然後我預計像下面應該產生的第一步代碼。但相反,它只是空白。

context.globalCompositeOperation = "destination-in"; 
var mask = [1, 1, 1, 1, 0, 1, 1, 1, 1]; 
for (var m = 0; m < 9; ++m) 
{ 
    var x = 10 + m % 3 * 150; 
    var y = 10 + Math.floor(m/3) * 150; 
    if (mask[m] > 0) 
    { 
     context.fillRect(x, y, 150, 150); 
    } 
} 

我把小提琴放在http://jsfiddle.net/128gxxmy/4/上以顯示問題。

這似乎並不是一件困難的事情,所以我明確地誤解了一些重要的東西,並會對任何建議表示感謝。

謝謝。

編輯:當然!我知道它爲什麼會變成空白。第一個填充矩形清除除左上角以外的所有內容,然後下一個清除。我需要一次性使用rect(...)然後填充()。如果我將它重新制作成一步即可完成每次傳球,那就應該有所斬獲。

回答

0

爲了完整和萬一其他人陷入同一陷阱,下面是相關的代碼。我最終使用了一個臨時(不可見)畫布,並繪製了一個填充整個圖層。

function drawLevel(k, fill, mask) 
{ 
    tempContext.save(); 
    tempContext.clearRect(0, 0, canvas.width, canvas.height); 

    // current canvas is destination 
    tempContext.drawImage(canvas, 0, 0); 
    // set global composite 
    tempContext.globalCompositeOperation = "destination-in"; 

    // draw source 
    tempContext.beginPath(); 

    // how many squares each row 
    var n = Math.pow(3, k); 

    var size = 450/n/3; 
    for (var i = 0; i < n; ++i) 
     for (var j = 0; j < n; ++j) 
     { 
      for (var m = 0; m < 9; ++m) 
      { 
       var x = 10 + i * size + m % 3 * size; 
       var y = 10 + j * size + Math.floor(m/3) * size; 
       if (mask[m] > 0) 
       { 
        tempContext.rect(x, y, size, size); 
       } 
      } 
     } 

    tempContext.fillStyle = fill; 
    tempContext.fill(); 
    tempContext.restore(); 

    // copy drawing from tempCanvas onto visible canvas 
    context.drawImage(tempCanvas, 0, 0); 
} 
相關問題