问题描述
我目前正在尝试接收画布的宽度和高度.画布使用的是样式参数,如下面的代码所示:
I'm currently trying to receive the width and height of a canvas. The canvas is using a style parameter as you can see in the following code:
<canvas id="ctx" style="height: calc(100vh - 142px); width: 100vw; display: block;"></canvas>
<script type="text/javascript">
var ctx = document.getElementById("ctx").getContext("2d");
console.log(ctx.width);
var socket = io();
socket.on('newPosition', function(data){
ctx.clearRect(0, 0, ctx.width, ctx.height);
ctx.fillText('P', data.x, data.y);
})
</script>
我尝试使用 console.log(ctx.width);
来获取值,该值返回了未定义的值.我认为出现问题是因为我使用样式标签将画布设置为自动调整大小.
I've tried to get the value using console.log(ctx.width);
which returned a undefined value. I think the problem occurs because im using the style tag to set the canvas to a autosize.
我如何以其他方式接收画布的宽度和高度?
How could i receive the canvas width and height in another way?
我感谢任何建议.
推荐答案
画布的宽度和高度是一种特殊情况.
The canvas is a special case when it comes to the width and height.
canvas.style.width
和 canvas.style.height
定义页面上显示的画布的宽度和高度.
The canvas.style.width
and canvas.style.height
define the width and height of the canvas as displayed on the page.
canvas.width
和 canvas.height
属性定义以像素为单位的画布大小或画布的分辨率.画布分辨率并不总是与画布显示尺寸匹配.
The canvas.width
and canvas.height
properties define the size of the canvas in pixels or the resolution of the canvas. The canvas resolution does not always match the canvas display size.
仅通过获取width和height属性即可获得画布分辨率.
You can get the canvas resolution by just getting the width and height properties.
var width = canvas.width;
var height = canvas.height;
画布分辨率的末尾没有任何单位,因此可以直接转换为 Number
. canvas.width
和 canvas.height
属性始终以像素为单位.
The canvas resolution will not have any units at the end so can be directly converted to a Number
. The canvas.width
and canvas.height
properties are always in pixels.
如果您未设置 canvas.width
和 canvas.height
属性,则画布分辨率默认为300 x 150.
If you do not set the canvas.width
and canvas.height
properties the canvas resolution will default to 300 by 150.
您可以通过 context.canvas
属性访问2D上下文画布.上下文没有width和height属性.
You can access the 2D context canvas via the context.canvas
property. The context does not have a width and height property.
// get resolution
var width = ctx.canvas.width;
var height = ctx.canvas.height;
// get display size. Note values will have units eg px,em,%
var displayWidth = ctx.canvas.style.width;
var displayHeight = ctx.canvas.style.height;
哦,并在评论中指出.样式属性只有在设置后才可用.
Oh and as pointed out in the comments. Style attributes will only be available if set.
这篇关于使用javascript获取画布的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!