2

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>

4 Answers4

2

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

body{
    background: -webkit-canvas(background);
}

JavaScript

var ctx = document.getCSSCanvasContext('2d', 'background', 300, 300);

// make some random rects
var i = 50;
while(i--){
    ctx.fillRect(Math.random()*300, Math.random()*300, Math.random()*50, Math.random()*50);
}

More Information on webkit method

More information on Firefox method

Loktar
  • 34,764
  • 7
  • 90
  • 104
1

if you were using jQuery

$('body').css("background-image", backgroundURL);
Zuriel
  • 1,848
  • 1
  • 19
  • 32
1

toDataURL method returns a URL equivalent., you need to place it in a place for a URL.

object.style.backgroundImage="url("+canvas.toDataURL()+")";

I would tag the body element with an ID for this.

document.getElementById("mypage").style.backgroundImage="url("+canvas.toDataURL()+")";

There are of course other ways to get the body object.

Update

per dontvotemedown, I believe you need argument for toDataURL()

Wayne
  • 4,760
  • 1
  • 24
  • 24
1

Like on this answer, you can try this:

$('body').css({'background-image':"url(" + canvas.toDataURL("image/png")+ ")" });
Community
  • 1
  • 1
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105