Centering a canvas

后端 未结 11 1608
野的像风
野的像风 2021-01-30 10:00

How do I markup a page with an HTML5 canvas such that the canvas

  1. Takes up 80% of the width

  2. Has a corresponding pixel h

11条回答
  •  感动是毒
    2021-01-30 10:45

    Same codes from Nickolay above, but tested on IE9 and chrome (and removed the extra rendering):

    window.onload = window.onresize = function() {
       var canvas = document.getElementById('canvas');
       var viewportWidth = window.innerWidth;
       var viewportHeight = window.innerHeight;
       var canvasWidth = viewportWidth * 0.8;
       var canvasHeight = canvasWidth / 2;
    
       canvas.style.position = "absolute";
       canvas.setAttribute("width", canvasWidth);
       canvas.setAttribute("height", canvasHeight);
       canvas.style.top = (viewportHeight - canvasHeight) / 2 + "px";
       canvas.style.left = (viewportWidth - canvasWidth) / 2 + "px";
    }
    

    HTML:

    
      
         Canvas is not supported.
      
    
    

    The top and left offset only works when I add px.

提交回复
热议问题