2016-02-02 60 views
4

我正在研究能夠在運行時將網頁的背景更改爲動態生成的圖像。我使用javascript和canvas元素來創建背景,我將其存儲在數組中,以便用戶可以在它們之間切換;圖像是JPEG文件使用javascript動態更改背景圖像

// canvas computations snipped 

var img = c.toDataURL("image/jpeg"); 
this.modifiedanimationarray[0] = new Image(); 
this.modifiedanimationarray[0].src = img; 

不過,我已經注意到,JavaScript來操縱的背景如下:

document.body.style.backgroundImage = "url('whatever.jpg')"; 

,它希望從URL的圖像,創建非動態。有什麼辦法可以強制document.body.style.backgroundImage接受一個即時創建的圖像,而不是隻加載一個域名?

+0

你是什麼意思? – Trix

+0

我的意思是生成響應用戶對網頁的操作,而不是從網站中提取圖像。因此,即時圖像是在需要時創建的。 – EventHorizon

+0

是的,它可以完成。檢查我更新的答案。看到這個在我的回答下行動 – Trix

回答

4

toDataURL會給你一個數據網址,可以用來代替普通的網址。因此,而不是做說

document.body.style.backgroundImage = 'url(someimage.jpg)'; 

只需更換網址,在這種情況下someimage.jpg,你從toDataURL

得到
document.body.style.backgroundImage = 'url('+canvas.toDataURL("image/jpeg")+')'; 

演示

function getBG(){ 
 
    var canvas = document.getElementById('bgcanvas'), 
 
     context = canvas.getContext('2d'), 
 
     cX = canvas.width/2, 
 
     cY = canvas.height/2; 
 
     context.beginPath(); 
 
     context.arc(cX, cY, 70, 0, 2 * Math.PI, false); 
 
     context.fillStyle = 'green'; 
 
     context.fill(); 
 
     context.stroke(); 
 
    return canvas.toDataURL("image/jpeg"); 
 
} 
 

 
document.body.style.backgroundImage = 'url('+getBG()+')';
canvas { 
 
    display:none; 
 
}
<canvas id="bgcanvas" width="200" height="200"></canvas>

網址另外請注意,你不需要加載一個數據網址在使用之前轉換成圖像對象。這意味着你不需要做:

var img = c.toDataURL("image/jpeg"); 
this.modifiedanimationarray[0] = new Image(); 
this.modifiedanimationarray[0].src = img; 

你會只是做

var img = c.toDataURL("image/jpeg"); 
this.modifiedanimationarray[0] = img; 
document.body.style.backgroundImage = 'url('+this.modifiedanimationarray[0]+')'; 
//or just 
document.body.style.backgroundImage = 'url('+img+')'; 
+0

謝謝,這似乎正是我想要的。恥辱我無法讓代碼的其餘部分工作! – EventHorizon

1

可以使用toDataURL的結果,像一個真正的URL。

var img = c.toDataURL("image/jpeg"); 
document.body.style.backgroundImage = "url(" + img + ")"; 
+0

所以,這樣的事情: \t this.modifiedanimationarray [0] = new Image(); \t this.modifiedanimationarray [0] .src = img; \t this.modifiedanimationarray [1] = new Image(); \t this.modifiedanimationarray [1] .src = img; document.body.style.backgroundImage =「url(」+ this.modifiedanimationarray [0] +「)」; and: document.body.style.backgroundImage =「url(」+ this.modifiedanimationarray [1] +「)」; – EventHorizon

+0

有一點我關心的是使用「src」標籤時,分配一個數組元素來「保存」所創建的圖像;在分配背景圖像時是否使用相同的標記,例如 document.body.style.backgroundImage =「url(」+ this.modifiedanimationarray [0]。src +「)」; 還是不?我認爲你不需要(??) – EventHorizon

+1

@EventHorizo​​n,如果'this.modifiedanimationarray [0] .src'是你存儲你從toDataURL獲得的數據url的地方,那麼你就是這樣使用它。請注意,儘管您不需要使用圖像對象來存儲/加載它,但您只需使用它。 –