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

后端 未结 8 1257
陌清茗
陌清茗 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:29

    It might be worth looking at a tutorial: MDN Canvas Tutorial

    You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

    var canvas = document.getElementById('mycanvas');
    var width = canvas.width;
    var height = canvas.height;
    

    If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

    const canvasW = canvas.getBoundingClientRect().width;
    const canvasH = canvas.getBoundingClientRect().height;
    

    Or using the shorter object destructuring syntax:

    const { width, height } = canvas.getBoundingClientRect();
    

    The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

提交回复
热议问题