【问题标题】:Loading Image into document.body Background将图像加载到 document.body 背景中
【发布时间】:2012-07-11 17:51:13
【问题描述】:

我正在尝试提取图像(在本例中为 /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 仍然是 ""

【问题讨论】:

  • document.body.style.background='url('+this.src+')';
  • 那么加载Image 对象有什么意义呢?我不能只做document.body.style.background=url("camera/frame");吗?
  • 是的,你不需要图片
  • 但我使用Image 的原因是它会在尝试绘制之前加载/缓存图像。

标签: javascript css image dom


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多