Centering a canvas

后端 未结 11 1598
野的像风
野的像风 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 11:01

    Resizing canvas using css is not a good idea. It should be done using Javascript. See the below function which does it

    function setCanvas(){
    
       var canvasNode = document.getElementById('xCanvas');
    
       var pw = canvasNode.parentNode.clientWidth;
       var ph = canvasNode.parentNode.clientHeight;
    
       canvasNode.height = pw * 0.8 * (canvasNode.height/canvasNode.width);  
       canvasNode.width = pw * 0.8;
       canvasNode.style.top = (ph-canvasNode.height)/2 + "px";
       canvasNode.style.left = (pw-canvasNode.width)/2 + "px";
    
    
    }
    

    demo here : http://jsfiddle.net/9Rmwt/11/show/

    .

提交回复
热议问题