Ben Shelock
Ben Shelock

Reputation: 20965

Use <canvas> as a CSS background

Can I use the canvas element as a css background?

Upvotes: 64

Views: 61208

Answers (8)

Vitalii Bobrov
Vitalii Bobrov

Reputation: 191

You can use CSS Paint API

.elem {
  backgound: paint(squares);
}

See more details here:

Blog posts:

https://vitaliy-bobrov.github.io/blog/exploring-the-css-paint-api/ https://vitaliy-bobrov.github.io/blog/css-paint-in-action-bar-chart/

Demos: https://vitaliy-bobrov.github.io/css-paint-demos/

Upvotes: 3

Jonathan
Jonathan

Reputation: 7088

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

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

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

Upvotes: 2

marzvrover
marzvrover

Reputation: 121

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

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

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>

Upvotes: 0

livedo
livedo

Reputation: 1067

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

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

<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 hacks for specifics.

Upvotes: 62

user1635543
user1635543

Reputation: 97

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

And -webkit-canvas(name) for CSS background in WebKit based browsers.

Upvotes: 3

frenchie
frenchie

Reputation: 51927

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

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 .toDataURL function. It works in every browser that supports canvas.

Upvotes: 59

Carlos Cabo
Carlos Cabo

Reputation: 741

I've been triying to achieve this same feature past weeks, the best solution I've found its the same proposed by 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)

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".

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>

Upvotes: 3

bcat
bcat

Reputation: 8941

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-image property. 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.

Upvotes: 12

Related Questions