2012-07-12 31 views
0

我試圖拉圖像(在這種情況下,/camera/frame,這是一個已知的好JPG),並加載它作爲我的document.body的背景。將圖像載入document.body背景

這裏是我的代碼迄今:

var backgroundImage = new Image(); 
backgroundImage.onload = function() 
{ 
    console.log("onload"); 
    document.body.style.backgroundImage = this.src; 
}; 

backgroundImage.src = 'camera/frame'; 

"onload"打印效果與預期,並this.src打印出完整的URL /camera/frame,但是document.body.style.backgroundImage仍然""

+4

'document.body.style.background ='url('+ this.src +')';' – bokonic 2012-07-12 01:57:56

+0

但是加載'Image'對象有什麼意義?我不能只是'document.body.style.background = url(「camera/frame」);'? – 2012-07-12 01:59:39

+0

絕對是 - 你不需要圖像 – bokonic 2012-07-12 02:03:10

回答

0

Canvas 2D to rescue!

var backgroundImage = new Image(); 
backgroundImage.onload = function() 
{  
    var canvas = document.getElementById('canvas'); 
    canvas.width = this.width; 
    canvas.height = this.height; 

    var canvasContext = canvas.getContext('2d'); 
    canvasContext.drawImage(this, 0, 0, this.width, this.height); 
}; 

backgroundImage.src = 'camera/frame'; 
backgroundImage.width = $(window).width(); 
backgroundImage.height = $(window).height(); 

在後臺加載圖像,然後將其無縫地繪製到畫布上!

1

我相信你可能會錯過兩件事。

var path = 'path/to/image.jpg'; 
document.body.style.background='url('+path+')';