Setting Canvas to Background - Javascript [duplica

2019-05-26 01:38发布

This question already has an answer here:

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条回答
可以哭但决不认输i
2楼-- · 2019-05-26 02:10

Like on this answer, you can try this:

$('body').css({'background-image':"url(" + canvas.toDataURL("image/png")+ ")" });
查看更多
beautiful°
3楼-- · 2019-05-26 02:16

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

查看更多
小情绪 Triste *
4楼-- · 2019-05-26 02:17

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()

查看更多
Luminary・发光体
5楼-- · 2019-05-26 02:23

if you were using jQuery

$('body').css("background-image", backgroundURL);
查看更多
登录 后发表回答