【问题标题】:Object.height returns half heightObject.height 返回半高
【发布时间】:2016-01-03 01:12:57
【问题描述】:

我有一个画布,我试图通过 JavaScript 获得它的高度,但它返回一半高度然后是实际高度

这是我正在使用的简单代码

var canvas = document.getElementById("clock");
var context = canvas.getContext("2d");

document.getElementById("status").innerHTML = canvas.height;
console.log(canvas.height);
canvas#clock{
	width:300px;
	height:300px;
	border:#D50003 1px solid;
	background:#1E1E1E;
}
<canvas id="clock"></canvas>
<div id="status"></div>

【问题讨论】:

  • 您没有在任何地方将高度设置为canvas,因此返回默认高度 150px。 300x150 的默认尺寸。对于画布,您需要使用内联 width/height 属性或使用诸如 canvas.width=300 之类的 javascript 设置大小
  • 我在 css 中将高度设置为 300px

标签: javascript html height


【解决方案1】:

画布的宽度和高度不是由 CSS 设置的,它们是由画布的 width 和 height 属性设置的。您看到 150 因为这是默认高度。来自MDN:

HTMLCanvasElement.height 属性是一个正整数,反映以 CSS 像素解释的元素的高度 HTML 属性。当未指定属性,或者设置为无效值(如负数)时,使用默认值 150。

CSS 的宽度和高度定义了画布所占据的布局空间。如果它们与画布大小不匹配,则画布将缩放以填充布局空间。例如,您在代码中所做的是采用 300x150 画布(默认尺寸)并将其拉伸以填充 300x300 区域。

而您可以使用getComputedStyle获取CSS应用的高度:

var height = getComputedStyle(canvas).height; // "300px"

...这不是 canvas 的高度,而是它在您的布局中占据的高度。

如果您在画布上设置宽度和高度,您将获得这些值(如果它们与 CSS 匹配,您的绘图将不会被拉伸/压缩):

var canvas = document.getElementById("clock");
var context = canvas.getContext("2d");

document.getElementById("status").innerHTML = canvas.height;
console.log(canvas.height);
canvas#clock{
	width:300px;
	height:300px;
	border:#D50003 1px solid;
	background:#1E1E1E;
}
<canvas id="clock" width="300" height="300"></canvas>
<div id="status"></div>

让我们证明您原始代码中的画布实际上是 300x150,通过在其上画一个圆圈将其拉伸到 300x300:

var canvas = document.getElementById("clock");
var context = canvas.getContext("2d");

document.getElementById("status").innerHTML = canvas.height;
console.log(canvas.height);
var ctx = canvas.getContext('2d');

var path = new Path2D();
path.arc(75, 75, 50, 0, Math.PI * 2, true);
ctx.fillStyle = ctx.strokeStyle = "blue";
ctx.fill(path);
canvas#clock {
  width: 300px;
  height: 300px;
  border: #D50003 1px solid;
  background: #1E1E1E;
}
<canvas id="clock"></canvas>
<div id="status"></div>

如您所见,由于我们使用画布的默认大小 300x150,但将其拉伸为 300x300,因此圆形被扭曲了。如果我们指定大小,它是正确的:

var canvas = document.getElementById("clock");
var context = canvas.getContext("2d");

document.getElementById("status").innerHTML = canvas.height;
console.log(canvas.height);
var ctx = canvas.getContext('2d');

var path = new Path2D();
path.arc(75, 75, 50, 0, Math.PI * 2, true);
ctx.fillStyle = ctx.strokeStyle = "blue";
ctx.fill(path);
canvas#clock {
  width: 300px;
  height: 300px;
  border: #D50003 1px solid;
  background: #1E1E1E;
}
<canvas id="clock" width="300" height="300"></canvas>
<div id="status"></div>

【讨论】:

  • 如果我使用 css 应用高度,我可以从任何方法获取高度值
猜你喜欢
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多