将图像加载到document.body背景中

时间:2012-07-12 01:54:40

标签: javascript css image dom

我正在尝试提取图片(在本例中为/camera/frame,这是一个已知良好的JPG),并将其加载为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打印出/camera/frame的完整网址,但document.body.style.backgroundImage仍为""

2 个答案:

答案 0 :(得分:1)

我相信你可能会遗漏两件事。

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

答案 1 :(得分:0)

Canvas 2D救援!

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();

在背景中加载图像,然后无缝地将其绘制到画布中!