Javascript 如何获取 HTML5 画布的宽度和高度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4032179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:12:45  来源:igfitidea点击:

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

javascripthtmlcanvas

提问by clamp

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

如何在 JavaScript 中获取画布元素的宽度和高度?

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

另外,我一直在读的画布的“上下文”是什么?

回答by andrewmu

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

可能值得看一个教程:Firefox 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:

如果画布元素中不存在宽度和高度属性,则将返回默认的 300x150 大小。要动态获取正确的宽度和高度,请使用以下代码:

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

Or using the shorter object destructuring syntax:

或者使用较短的对象解构语法:

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

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

context是一个你从画布上得到的对象,允许你在它里面画画。您可以将其context视为画布的 API,它为您提供了使您能够在画布元素上绘图的命令。

回答by Bitterblue

Well, all the answers before aren't entirely correct. 2 of major browsers don't support those 2 properties (IE is one of them) or use them differently.

好吧,之前的所有答案都不完全正确。2 个主要浏览器不支持这 2 个属性(IE 是其中之一)或以不同方式使用它们。

Better solution (supported by most browsers, but I didn't check Safari):

更好的解决方案(大多数浏览器都支持,但我没有检查 Safari):

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

At least I get correct values with scrollWidth and -Height and MUST set canvas.width and height when it is resized.

至少我得到了正确的 scrollWidth 和 -Height 值,并且在调整大小时必须设置 canvas.width 和 height。

回答by Dan Dascalescu

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

提到的答案canvas.width返回画布的内部尺寸,即创建元素时指定的尺寸:

<canvas width="500" height="200">

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

如果您使用 CSS 调整画布大小,则可以通过.scrollWidth和访问其 DOM 尺寸.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);
<p id="dom-dims"></p>
<p id="internal-dims"></p>
<canvas style="width: 100%; height: 123px; border: 1px dashed black">

回答by Harmen

The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.

上下文对象允许您操作画布;例如,您可以绘制矩形等等。

If you want to get the width and height, you can just use the standard HTML attributes widthand height:

如果你想获得宽度和高度,你可以使用标准的 HTML 属性widthheight

var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );

alert( canvas.width );
alert( canvas.height ); 

回答by halfbit

now starting 2015 all (major?) browsers seem to alow c.widthand c.heightto get the canvas internalsize, but:

现在从 2015 年开始,所有(主要?)浏览器似乎都变低了c.widthc.height获得了画布内部大小,但是:

the question as the answers are missleading, because the a canvas has in principle 2 different/independent sizes.

作为答案的问题具有误导性,因为画布原则上有 2 个不同/独立的尺寸。

The "html" lets say CSS width/height and its own (attribute-) width/height

“html”让我们说 CSS 宽度/高度和它自己的(属性-)宽度/高度

look at this short example of different sizing, where I put a 200/200 canvas into a 300/100 html-element

看看这个不同大小的简短示例,我将 200/200 的画布放入 300/100 的 html 元素

With most examples (all I saw) there is no css-size set, so theese get implizit the width and height of the (drawing-) canvas size. But that is not a must, and can produce funy results, if you take the wrong size - ie. css widht/height for inner positioning.

大多数示例(我所看到的)都没有设置 css-size,因此这些示例会隐含(绘图)画布大小的宽度和高度。但这不是必须的,如果您选择错误的尺寸 - 即会产生有趣的结果。用于内部定位的 css 宽度/高度。

回答by Subtopic

None of those worked for me. Try this.

这些都不适合我。尝试这个。

console.log($(canvasjQueryElement)[0].width)

回答by DoomGoober

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

这是一个 CodePen,它使用 canvas.height/width、CSS 高度/宽度和上下文来正确呈现任何大小的任何画布

HTML:

HTML:

<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>

CSS:

CSS:

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

Javascript:

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.

基本上, canvas.height/width 设置您要渲染的位图的大小。CSS 高度/宽度然后缩放位图以适应布局空间(通常在缩放时扭曲它)。然后上下文可以修改它的比例以使用矢量操作以不同的大小进行绘制。

回答by Brian Sanchez

I had a problem because my canvas was inside of a container without ID so I used this jquery code below

我遇到了一个问题,因为我的画布在一个没有 ID 的容器内,所以我在下面使用了这个 jquery 代码

$('.cropArea canvas').width()