Javascript 使用 <canvas> 作为 CSS 背景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3397334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:28:34  来源:igfitidea点击:

Use <canvas> as a CSS background

javascriptcsscanvas

提问by Ben Shelock

Can I use the canvas element as a css background?

我可以使用 canvas 元素作为 css 背景吗?

回答by livedo

This has been possible in WebKit since 2008, see here.

自 2008 年以来,这在 WebKit 中已成为可能,请参见此处

<html>
 <head>
 <style>
 div { background: -webkit-canvas(squares); width:600px; height:600px; border:2px solid black }
 </style>

 <script type="application/x-javascript">
function draw(w, h) {
 var ctx = document.getCSSCanvasContext("2d", "squares", w, h);

 ctx.fillStyle = "rgb(200,0,0)";
 ctx.fillRect (10, 10, 55, 50);

 ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
 ctx.fillRect (30, 30, 55, 50);
}
 </script>
 </head>
 <body onload="draw(300, 300)">
   <div></div>
 </body>

</html>

Currently, Firefox 4 contains a feature, which allows you to use any element (including canvas) as a CSS background, in this fashion:

目前,Firefox 4 包含一项功能,允许您以这种方式使用任何元素(包括画布)作为 CSS 背景:

<p id="myBackground1" style="background: darkorange; color: white;  width: 300px; height: 40px;">
  This element will be used as a background.
</p>
<p style="background: -moz-element(#myBackground1); padding: 20px 10px; font-weight: bold;">
  This box uses #myBackground1 as its background!
</p>

See Mozilla hacksfor specifics.

有关详细信息,请参阅Mozilla hacks

回答by frenchie

Yes!!!! You can put a canvas in CSS background.

是的!!!!您可以在 CSS 背景中放置一个画布。

var Canvas = document.createElement("canvas");
... do your canvas drawing....
$('body').css({'background-image':"url(" + Canvas.toDataURL("image/png")+ ")" });

I know this is a pretty old question but I felt like posting my answer for people who'd visit this page because this is the correct answer, in just one line of code, using the .toDataURLfunction. It works in every browser that supports canvas.

我知道这是一个很老的问题,但我想为访问此页面的人发布我的答案,因为这是正确的答案,只需一行代码,使用该.toDataURL函数。它适用于所有支持画布的浏览器。

回答by bcat

I think the closest you could get is to render into a canvas, call toDataUrl()on it to retrieve the contents as an image, and assignment that result to the desired element's background-imageproperty. This will only give a static background, though. If you want to be able to further update the canvas, however, then you'll need to instead position the canvas behind another element, as Johan has already suggested.

我认为你能得到的最接近的是渲染成canvas,调用toDataUrl()它以将内容检索为图像,并将结果分配给所需元素的background-image属性。不过,这只会提供静态背景。canvas但是,如果您希望能够进一步更新,那么您需要将画布放置在另一个元素后面,正如 Johan 已经建议的那样。

回答by Putuko

I've been triying to achieve this same feature past weeks, the best solution I've found its the same proposed by bcat:

我一直triying达到过去几周此相同的功能,最好的解决办法,我发现它的提出同样的BCAT

  1. Render canvas (visible or hidden)
  2. Get canvas image with "canvas.toDataURL"
  3. Asign this image-data as background image for the element (I use MooTools)
  1. 渲染画布(可见或隐藏)
  2. 使用“canvas.toDataURL”获取画布图像
  3. 将此图像数据指定为元素的背景图像(我使用 MooTools)

The bad news, for static images works great, but with animation in Chrome sometimes "blinks", and in Firefox blinks-a-lot. Maybe someone knows a workaround to get rid of this "nasty blinking".

坏消息是,静态图像效果很好,但 Chrome 中的动画有时会“闪烁”,而 Firefox 中会闪烁很多。也许有人知道一种解决方法来摆脱这种“讨厌的眨眼”。

Best regards.
P:.

此致。
普:。

<!DOCTYPE html>
<html>
<head>
<title>Asign canvas to element background</title>
<script type="text/javascript" src="/js/mootools.1.2.4.js"></script>
<style type="text/css">
* {
    outline:0;
    padding:0;
    margin:0;
    border:0;
}
body {
    color:#fff;
    background:#242424;
}
</style>
<script>
window.addEvent('domready',function() {

//GET BODY
var mibodi = $('mibodi');
var viewportSize = mibodi.getSize();

//GET CANVAS
var micanvas = $('micanvas');
var ctx = micanvas.getContext('2d');
var playAnimation = true;

//GET DIV
var midiv = $('midiv');

//VARIABLES
var rotate_angle = 0;
var rotate_angle_inc = 0.05;

//FUNCIóN DE INICIALIZACIóN
function init(){

    ctx.clearRect (0, 0, 512, 512); //CLEAR CANVAS
    ctx.fillStyle = 'rgba(128,128,128,1)';
    ctx.strokeStyle = 'rgba(255,255,255,1)';

    if (playAnimation) {
    setInterval(draw,100);//
  }

} //INIT

//FUNCIóN DE DIBUJADO
function draw() {

    //CLEAR BACKGROUND
    ctx.clearRect (0, 0, 512, 512);

    //DRAW ROTATING RECTANGLE
    ctx.save();
    ctx.translate( micanvas.width / 2, micanvas.height / 2 );
    ctx.rotate( rotate_angle );
    ctx.fillRect(0, 0, 100, 100);
    ctx.restore();

    //GET CANVAS IMAGE
    var dataURL = micanvas.toDataURL("image/png");

    //SET IMAGE AS BACKGROUND OF THE ELEMENTS
    midiv.setStyle('background-image', 'url(' + dataURL + ')');
    mibodi.setStyle('background-image', 'url(' + dataURL + ')');

    //ANGLE INCREMENT
    rotate_angle = rotate_angle + rotate_angle_inc;

} //DRAW

//BEGIN TO DRAW
init();

});//domeady

</script>
</head>
<body id="mibodi" >

<canvas id="micanvas" width="512" height="512" style="float:left;" style="display:none;">
Este texto se muestra para los navegadores no compatibles con canvas.
<br>
Por favor, utiliza Firefox, Chrome, Safari u Opera.
</canvas>

<div id="midiv" style="width:512px;height:512px;background:#f00;float:left;">
    Sample
</div>

</body>
</html>

回答by user1635543

Try -moz-element(#id)for CSS backgroundin Firefox.

在 Firefox 中尝试-moz-element(#id)使用 CSS background

And -webkit-canvas(name)for CSS backgroundin WebKitbased browsers.

-webkit-canvas(name)对CSSbackgroundWebKit的基于浏览器。

回答by Jonathan

You can emulate this behavior quickly without the performance drop of toDataURL()using z-index(granted, it's a workaround, since CSS images 4 / CSS Houdini hasn't implemented "background: element(#mycanvas)" as of 2017))

您可以快速模拟此行为而不会降低toDataURL()使用性能z-index(当然,这是一种解决方法,因为截至 2017 年,CS​​S 图像 4 / CSS Houdini 尚未实现“背景:元素(#mycanvas)”))

Working JSFiddle here. I didn't write this, all credit goes to Derek Leung:

在这里工作 JSFiddle。这不是我写的,所有功劳都归功于Derek Leung

http://jsfiddle.net/DerekL/uw5XU/

http://jsfiddle.net/DerekL/uw5XU/

回答by MDooley47

Unable to comment so I will create my own answer for this.

无法发表评论,因此我将为此创建自己的答案。

This answer is based off of @livedo, @Eric Rowell, and @shabunc

此答案基于 @livedo、@Eric Rowell 和 @shabunc

http://jsfiddle.net/MDooley47/yj26psdb/

http://jsfiddle.net/MDooley47/yj26psdb/

window.i = 0;
function draw(w, h) {
    window.i+=5;
    if (window.webkitURL != null) {
        var ctx = document.getCSSCanvasContext("2d", "squares", 100, 100);


        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, w, h);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";

        ctx.fillRect (30, 30, w, h);
    }
    else {
        var ctxmozc = document.getElementById("squares");
        var ctxmoz = ctxmozc.getContext("2d");

        ctxmoz.fillStyle = "rgb(200,0,0)";
        ctxmoz.fillRect (10, 10, w, h);

        ctxmoz.fillStyle = "rgba(0, 0, 200, 0.5)";

        ctxmoz.fillRect (30, 30, w, h);
    }
}
setInterval(function(){draw(window.i, window.i);}, 500);
 div {
     background: -webkit-canvas(squares);
     background: -moz-element(#squares) repeat-x;
     width:575px;
     height:475px;
     border:2px solid black
 }
<body>
    <div></div>
    <canvas id="squares" name="squaresmoz" style="display: none;" ></canvas>
</body>