javascript - 如何在后台设置 BPG

标签 javascript html css background-image bpg

我可以使用 BPG 吗?图片为 <div><body>背景? background: url('bg.bpg');不起作用。

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

最佳答案

Javascript BPG 解码器通过将源 .bpg 文件转换为 ImageData 来工作。对象,然后可以将其绘制到 Canvas 上。所以你需要做的就是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>

关于javascript - 如何在后台设置 BPG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28088036/

相关文章:

javascript - 计算多种货币格式元素的总和

javascript - 模板未显示在 angularjs + rails 应用程序中

javascript - OnsenUI 显示页面

html - CSS 背景渐变显示不适合大屏幕

html - 没有表单的按钮在 Firefox 中看起来很糟糕

css - React Native 中的提升

javascript - 我有一条消息输出,我希望有一个词橙色,其余正常

javascript - 所有的全局变量和全局函数都是 `window`对象的成员吗?

html - 第 n 个 child 无法正常工作,有时计数错误

css - 仅使用 CSS 从中心旋转三 Angular 形图像?