如何在背景上设置BPG

4

我能否将BPG图像用作<div><body>背景?使用background: url('bg.bpg');无效。

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


在哪个浏览器中?更重要的是,目前有没有任何浏览器支持.bpg文件? - GoBusto
但是有一个 JavaScript 解码器可以显示 BPG。 - user3041764
我建议你在问题中提到这一点 - 可能是脚本没有被加载,或者其他地方的错误阻止了Javascript运行,或者Javascript代码中存在错误,或者可能是浏览器特定的问题。请尽可能添加更多信息! - GoBusto
我正在使用http://bellard.org/bpg/上的标准示例,它可以正确地显示图像,但我不想显示img而是将img设置为body背景。 - user3041764
1
请编辑您的问题以包含此信息,而不是在评论中添加它-这有助于更多人注意到它。 - GoBusto
1个回答

12

Javascript BPG解码器的工作原理是将源.bpg文件转换为一个ImageData对象,然后可以绘制到画布上。因此,您只需获取画布作为PNG数据字符串,并将其设置为网页背景图像:

<!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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接