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

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

    Here's a CodePen that uses canvas.height/width, CSS height/width, and context to correctly render any canvas at any size.

    HTML:

    
    
    

    CSS:

    canvas {
      width: 400px;
      height: 200px;
      border: 1px solid red;
      display: block;
    }
    

    Javascript:

    const myCanvas = document.getElementById("myCanvas");
    const originalHeight = myCanvas.height;
    const originalWidth = myCanvas.width;
    render();
    function render() {
      let dimensions = getObjectFitSize(
        true,
        myCanvas.clientWidth,
        myCanvas.clientHeight,
        myCanvas.width,
        myCanvas.height
      );
      myCanvas.width = dimensions.width;
      myCanvas.height = dimensions.height;
    
      let ctx = myCanvas.getContext("2d");
      let ratio = Math.min(
        myCanvas.clientWidth / originalWidth,
        myCanvas.clientHeight / originalHeight
      );
      ctx.scale(ratio, ratio); //adjust this!
      ctx.beginPath();
      ctx.arc(50, 50, 50, 0, 2 * Math.PI);
      ctx.stroke();
    }
    
    // adapted from: https://www.npmjs.com/package/intrinsic-scale
    function getObjectFitSize(
      contains /* true = contain, false = cover */,
      containerWidth,
      containerHeight,
      width,
      height
    ) {
      var doRatio = width / height;
      var cRatio = containerWidth / containerHeight;
      var targetWidth = 0;
      var targetHeight = 0;
      var test = contains ? doRatio > cRatio : doRatio < cRatio;
    
      if (test) {
        targetWidth = containerWidth;
        targetHeight = targetWidth / doRatio;
      } else {
        targetHeight = containerHeight;
        targetWidth = targetHeight * doRatio;
      }
    
      return {
        width: targetWidth,
        height: targetHeight,
        x: (containerWidth - targetWidth) / 2,
        y: (containerHeight - targetHeight) / 2
      };
    }
    

    Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.

提交回复
热议问题