An html5 canvas element in the background of my page?

前端 未结 4 1787
忘了有多久
忘了有多久 2020-12-07 14:07

Is it possible to have a full screen canvas element in the background of a webpage and \"normal\" markup elements like a table in front of it?

like the following sni

4条回答
  •  轮回少年
    2020-12-07 14:36

    You can use toDataURL() to have it in pure JS separated from HTML

    var c = document.createElement('canvas'),        
        ctx = c.getContext('2d'),
        size = c.width = c.height = 50;
    
    for( var x = 0; x < size; x++ ){
        for( var y = 0; y < size; y++ ){
            ctx.fillStyle = 'hsl(0, 0%, ' + ( 100 - ( Math.random() * 15 ) ) + '%)';
            ctx.fillRect(x, y, 1, 1);
        }
    }
    
    document.body.style.background = 'url(' + c.toDataURL() + ')';
    HTML on canvas background

    Based on this CodePen

提交回复
热议问题