HTML5 Canvas 100% height and width

前端 未结 2 1769
囚心锁ツ
囚心锁ツ 2021-02-08 11:20

I\'m trying to make this raindrop canvas script take up 100% width and height, but nothing I seem to do works. I tried changing the CSS, and height/width in the Canvas area, but

相关标签:
2条回答
  • 2021-02-08 11:52

    I've set up a fiddle that shows how to resize the canvas using some simple CSS.

    http://jsfiddle.net/C7LfU/1/

    $('#canvasRain').css({
       "height": window.innerHeight,
       "width": window.innerWidth
    });
    

    I've also went ahead and updated your animation to use requestAnimationFrame. This probably what caused your Flakes to be fuzzy: The animation lagged since setTimeout doesn't scale to when the browser is actually ready to draw another frame.

    window.requestAnimFrame = (function () {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    })();
    
    function animate() {
        requestAnimFrame(animate);
        Update();
        Draw();
    }
    

    Read a little more about why you should use requestAnimationFrame at: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/

    0 讨论(0)
  • 2021-02-08 11:57

    body, #canvasRain {width:100%; height:100%; margin:0px;} will set your size properly but your problem is that your canvas height/width you're using to do your drawing doesn't pick up the proper px values when setting them with %'s. And that's where the scaling comes in with the fuzzy flakes. It takes some default canvas size and stretches to 100% of the view. Adding something like

    bufferCanvas.width = canvas.width = window.innerWidth;
    bufferCanvas.height = canvas.height = window.innerHeight;
    

    seems to do the trick. And you might want/need to handle resize events to recalculate it. Here is a sample. I couldn't get jsFiddle to work for me, so it's just the whole thing.

    0 讨论(0)
提交回复
热议问题