Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set canvas element as background of a div element

Tags:

html

css

We can use canvas for drawing custom shapes. I need to draw my shape dynamically as a canvas item and place it for a div background item. My pages generates run time and they aren't static html code so i can't use tricky methods. What's your idea?

Regards

like image 604
Saman Gholami Avatar asked Apr 15 '13 08:04

Saman Gholami


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.

Can you put a canvas in a div?

To add a scrollable canvas inside a div, we can make the div scrollable and put a canvas inside it. to add a div with the overflow CSS property set to auto . And then we add a canvas inside it with a red border.

Can you put a background image in a div?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.


2 Answers

Looks like you searching for toDataURL().

UPD: Here a usage exaple:

dataUrl = your_canvas.toDataURL();
your_div.style.background='url('+dataUrl+')'

Live demo on jsFiddle

like image 67
Arthur Halma Avatar answered Nov 15 '22 08:11

Arthur Halma


Sounds like you need canvas2image: https://github.com/hongru/canvas2image

You can create a canvas and then get the contents as a png:

var canvas = document.createElement("canvas");

....do stuff here...

var img = Canvas2Image.convertToPNG(canvas, canvas.width, canvas.height);

Then all you need to do is use the png as a background image:

document.body.style.background = "url(" + img.src + ")";

Please correct me if any of this is wrong.

like image 43
starbeamrainbowlabs Avatar answered Nov 15 '22 08:11

starbeamrainbowlabs