正在将图像加载到文档中.正文背景

Loading Image into document.body Background

本文关键字:文档 正文 背景 加载 图像      更新时间:2023-09-26

我正在尝试提取一个图像(在本例中为/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的完整URL,但document.body.style.backgroundImage仍然是""

我相信您可能遗漏了两件事。

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

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

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