GoldenNewby
GoldenNewby

Reputation: 4452

HTML5 Canvas as CSS background-image?

Is it possible to make the background image of a DIV a canvas that can be modified with getContext("2d")?

Upvotes: 10

Views: 21382

Answers (3)

Zeta
Zeta

Reputation: 105995

Well, you could place a canvas element inside of the div, maximize its height and width, set its position to relative and its z-index to a negative value.

However, if you want to use a real CSS background-image:... you would have to create your image inside your canvas. You could then use toDataURL to get a data url which you could use as value for your original background-image:

var canvas = document.getElementById('canvas');
var data = canvas.toDataURL();
var myElement = document.getElementById('myelement');

myElement.style.backgroundImage = 'url('+data+')';

If you don't want to create a new background but manipulate an existing one, load your original background into an Image object (or get a reference) and use drawImage:

var image = new Image();
image.onload = function(){
    context.drawImage(this,0,0);
    someCallbackToManipulateTheImage();
}
var src = myElement.style.backgroundImage.substr(4);
src.substr(0,src.length - 1);
image.src = src;

Upvotes: 31

Josh1billion
Josh1billion

Reputation: 14927

Set the background-image of the div to this:

"url('" + canvas.toDataURL() + "')";

Edit: At that point, note that you are also free to do what you wish with the canvas, as the background-image will continue to contain only the image data that was in the canvas at the moment that you called canvas.toDataURL(). Feel free to discard or draw onto the canvas, as it will not affect your div's background at that point.

Upvotes: 8

Linh Nguyen
Linh Nguyen

Reputation: 659

You can have a canvas inside the div with absolute css position, other elements have to have z-index greater than the canvas.

Upvotes: -3

Related Questions