How to get width and height of canvas after resizing the browser

前端 未结 1 363
执念已碎
执念已碎 2021-01-16 07:18

I want to get width and height of canvas which is responsive. I have 5 canvas elements on a single page.

Using Javascript before drawing I want to know the height an

相关标签:
1条回答
  • 2021-01-16 07:43

    Usually you don't set size of canvas using CSS but calculating the w/h and use the width and height properties.

    But if you use CSS you can get the calculated size of the canvas element set by CSS using getComputedStyle():

    Online demo

    var cs     = getComputedStyle(canvas);
    var width  = parseInt( cs.getPropertyValue('width'), 10);
    var height = parseInt( cs.getPropertyValue('height'), 10);
    

    the size is here returned by getPropertyValue() as a string and in pixel size (ie. "400px"), so we use parseInt() to chop of the "px" part.

    Then simply set the width and height on canvas and update its content.

    Full example (adjust as needed):

    window.onresize = updateCanvas;
    
    updateCanvas();
    
    function updateCanvas() {
    
        var cs = getComputedStyle(canvas);
        var width = parseInt(cs.getPropertyValue('width'), 10);
        var height = parseInt(cs.getPropertyValue('height'), 10);
        
        canvas.width = width;
        canvas.height = height;
        
        var ctx = canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(width, height);
        ctx.moveTo(0, height);
        ctx.lineTo(width, 0);
        ctx.stroke();
    }
    
    0 讨论(0)
提交回复
热议问题