Canvas How to - Create dynamic background image for div element








Question

We would like to know how to create dynamic background image for div element.

Answer


<!-- ww w  . j  ava 2  s .c o  m-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
div {
  width: 400px;
  height: 400px;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    var centerX = 70;
    var centerY = 70;
    var radius = 70;
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = "#8ED6FF";
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = "black";
    context.stroke();
    var img = canvas.toDataURL("image/png");
    var b = document.getElementById("foo");
    b.style.backgroundImage = "url(" + img + ")";
}//]]>  
</script>
</head>
<body>
  <div id="foo"></div>
</body>
</html>

The code above is rendered as follows: