Canvas How to - Create background image from canvas








Question

We would like to know how to create background image from canvas.

Answer


<!--   www. j  a v  a2 s  .  c  o m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.1.js'></script>

<script type='text/javascript'>//<![CDATA[ 
$(function(){
    var canvas = document.getElementById("acanvas");
    canvas.width = 10;
    canvas.height = 10;
    var context = canvas.getContext("2d");
    context.fillStyle = "rgba(0, 0, 255, .5)";
    context.fillRect(0, 0, 5, 5);
    context.fillRect(5, 5, 5, 5);
    $("#adiv").css ( {
        "background": "url("+canvas.toDataURL()+")"
    });
});//]]>  
</script>
</head>
<body>
  <div id="adiv"></div>
  <canvas id="acanvas"></canvas>
</body>
</html>

The code above is rendered as follows: