This question already has an answer here:
- Use <canvas> as a CSS background 8 answers
I am trying to figure out how to turn the canvas I have created into the background image of the HTML body. Thanks!
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
canvas.style.background = '#D1E0FF';
var context = canvas.getContext("2d");
for (i=0; i<20; i++) {
context.fillStyle = '#FF8533';
context.fillRect (
Math.round(Math.random()*300*100)/100,
Math.round(Math.random()*300*100)/100,
30,
30
);
}
var backgroundURL = canvas.toDataURL();
???
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="300px" height="300px"></canvas>
</body>
Like on this answer, you can try this:
With CSS you can use
-webkit-canvas
of course only on webkit browsers. To achieve a similar effect on Firefox you would use-moz-element
Live demo
CSS
JavaScript
More Information on webkit method
More information on Firefox method
toDataURL method returns a URL equivalent., you need to place it in a place for a URL.
I would tag the body element with an ID for this.
There are of course other ways to get the body object.
Update
per dontvotemedown, I believe you need argument for toDataURL()
if you were using jQuery