How do I get the width and height of a HTML5 canvas?

后端 未结 8 1241
陌清茗
陌清茗 2020-12-13 17:04

How can i get the width and height of the canvas element in JavaScript?

Also, what is the \"context\" of the canvas I keep reading about?

8条回答
  •  自闭症患者
    2020-12-13 17:11

    The answers mentioning canvas.width return the internal dimensions of the canvas, i.e. those specified when creating the element:

    
    

    If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth and .scrollHeight:

    var canvasElem = document.querySelector('canvas');
    document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +
          canvasElem.scrollWidth +
          ' x ' +
          canvasElem.scrollHeight
    
    var canvasContext = canvasElem.getContext('2d');
    document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +
          canvasContext.canvas.width +
          ' x ' +
          canvasContext.canvas.height;
    
    canvasContext.fillStyle = "#00A";
    canvasContext.fillText("Distorted", 0, 10);

提交回复
热议问题