Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas as CSS background-image?

Tags:

html

css

canvas

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

like image 745
GoldenNewby Avatar asked Apr 02 '12 05:04

GoldenNewby


People also ask

Can I use canvas as background?

You can use a canvas element as a background, but CSS doesn't have anything to do with that. Yes you can!!!! $('body'). css({'background-image':"url(" + Canvas.

Can you style canvas with CSS?

Because the canvas is an HTML element, you can use CSS styles to modify its position, assign it a background color or image, add a border, and so on. In Safari and other WebKit-based browsers, you can use WebKit transitions to smoothly animate changes in CSS properties.

How do you save an HTML5 Canvas as an image on a server?

Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image.

Is HTML5 Canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.


2 Answers

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;
like image 137
Zeta Avatar answered Sep 21 '22 17:09

Zeta


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.

like image 33
Josh1billion Avatar answered Sep 20 '22 17:09

Josh1billion