如何在背景上设置BPG

时间:2015-01-22 11:46:22

标签: javascript html css background-image bpg

我可以将BPG图片用作<div><body>背景吗? background: url('bg.bpg');无效。

有一个Javascript解码器允许.bpg图像显示在<img>标签中,但我想将其中一个用作<body>背景。

1 个答案:

答案 0 :(得分:12)

Javascript BPG解码器的工作原理是将源.bpg文件转换为ImageData对象,然后可以将其绘制到画布上。所以你需要做的就是get the canvas as a PNG data string并将其设置为身体背景图像:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>BPG background example.</title>
        <!-- Decoder script from http://bellard.org/bpg/ -->
        <script src="bpgdec8a.js"></script>
        <script>
"use strict";

function setBackground(filename)
{

  // Create a hidden canvas with the same dimensions as the image.
  var canvas = document.createElement("canvas");
  canvas.style.visibility = "hidden";
  canvas.width = 512;
  canvas.height = 512;
  document.body.appendChild(canvas);

  // Create a drawing context and a BPG decoder.
  var ctx = canvas.getContext("2d");
  var img = new BPGDecoder(ctx);

  // Attempt to load the image.
  img.onload = function()
  {
    // Once the image is ready, draw it to the canvas...
    ctx.putImageData(this.imageData, 0, 0);
    // ...and copy the canvas to the body background.
    document.body.style.background = "url('" + canvas.toDataURL("image/png") + "')";
  };
  img.load(filename);

}
        </script>
    </head>
    <body onload="setBackground('lena512color.bpg');">
        <p>Hello, World!</p>
    </body>
</html>