2012-02-01 125 views
2

我有一個64x64的畫布方形元素,我想在x和y方向上重複以填充頁面。我發現了很多關於如何用圖像做這個的解釋,但沒有解釋如何用canvas元素做到這一點。這是我到目前爲止的代碼:HTML5畫布 - 重複畫布元素作爲圖案

$(document).ready(function(){ 
    var canvas = document.getElementById('dkBg'); 
    var ctx = canvas.getContext('2d'); 
    ctx.canvas.width = window.innerWidth; 
    ctx.canvas.height = window.innerHeight; 
    ctx.fillStyle = 'rgb(0,0,0)'; 
    //I want the following rectangle to be repeated: 
    ctx.fillRect(0,0,64,64); 
    for(var w=0; w<=64; w++){ 
      for(var h=0; h<=64; h++){ 
        rand = Math.floor(Math.random()*50); 
        while(rand<20){ 
          rand = Math.floor(Math.random()*50); 
        } 
        opacity = Math.random(); 
        while(opacity<0.5){ 
          opacity = Math.random(); 
        } 
        ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')'; 
        ctx.fillRect(w,h,1,1); 
      } 
    } 
}); 

的事情是,我希望所有的隨機數的/ etc再生。我只想平鋪完全相同的正方形以適合頁面。這可能嗎?

這裏是一個小提琴:http://jsfiddle.net/ecMDq/

回答

4

做你想做的事實際上是超級簡單。您根本不需要使用圖像。 createPattern函數接受圖像另一個畫布! (或一個視頻標籤,甚至)

所有你需要做的是製作一個只有64x64大的畫布,並在上面製作圖案。我們把這個畫布稱爲pattern。你只需要做一次設計。

然後與主畫布的背景下,我們可以這樣做:

// "pattern" is our 64x64 canvas, see code in fiddle 
var pattern = ctx.createPattern(pattern, "repeat"); 
ctx.fillStyle = pattern; 

工作示例使用您的代碼,以使圖案,然後重複它到500×500的畫布:

http://jsfiddle.net/tGa8M/

+0

感謝您的支持。我選擇了這個答案,因爲它更簡單,看起來更像一個更好的方法。 – 2012-02-01 22:14:41

2

可以使用canvas元素的toDataURL()方法來獲取圖像的BASE64版本。

從那裏,它是爲你的頁面的背景圖像設置爲字符串"url(" + base64 + ")"

這裏是一個工作示例一樣簡單:http://jsfiddle.net/ecMDq/1/

$(document).ready(function(){ 
    var canvas = document.getElementById('dkBg'); 
    var ctx = canvas.getContext('2d'); 
    ctx.canvas.width = 64; //window.innerWidth; 
    ctx.canvas.height = 64; //window.innerHeight; 
    ctx.fillStyle = 'rgb(0,0,0)'; 
    //I want the following rectangle to be repeated: 
    ctx.fillRect(0,0,64,64); 
    for(var w=0; w<=64; w++){ 
      for(var h=0; h<=64; h++){ 
        rand = Math.floor(Math.random()*50); 
        while(rand<20){ 
          rand = Math.floor(Math.random()*50); 
        } 
        opacity = Math.random(); 
        while(opacity<0.5){ 
          opacity = Math.random(); 
        } 
        ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')'; 
        ctx.fillRect(w,h,1,1); 
      } 
    } 

    document.documentElement.style.backgroundImage = 
     'url(' +canvas.toDataURL() + ')'; 

}); 

請注意,你需要做畫布64×64,因爲這是您的源圖像的大小。 您現在也可以製作畫布display:none,甚至可以將它完全從dom中移除,因爲它僅充當背景圖像的來源。

另外,什麼在地球上與那些while循環?

while(rand<20){ 
     rand = Math.floor(Math.random()*50); 
} 

看起來你試圖執行一個最小值。只要使用這個:

rand = Math.floor(Math.random() * (50-20) + 20); 
+0

謝謝爲這個答案。雖然我沒有選擇它,但我從來沒有想到會這樣做,我覺得它很有趣。我可能會在未來使用這種技術,但在這一點上,我希望將所有內容都放在畫布標籤中,而不是使用背景圖像。 – 2012-02-01 22:16:38