我有一个画布,我试图通过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>
&#13;
答案 0 :(得分:5)
画布的宽度和高度不是由CSS设置的,而是由画布的width
和height
属性设置的。您已经看到了150,因为它是默认高度。来自MDN:
HTMLCanvasElement.height属性是一个正整数,反映了以CSS像素解释的元素的高度HTML属性。如果未指定属性,或者将其设置为无效值(如负值),则使用默认值150.
CSS宽度和高度定义画布占用的布局空间。如果它们与画布大小不匹配,则画布缩放以填充布局空间。例如,您在代码中执行的操作是使用300x150画布(默认尺寸)并将其拉伸以填充300x300区域。
虽然可以使用getComputedStyle
获取CSS应用的高度:
var height = getComputedStyle(canvas).height; // "300px"
......那不是画布的高度,而是它在你的布局中占据的高度。
如果在画布上设置宽度和高度,您将获得这些值(如果它们与CSS匹配,并且您的绘图不会被拉伸/压缩):
var canvas = document.getElementById("clock");
var context = canvas.getContext("2d");
document.getElementById("status").innerHTML = canvas.height;
console.log(canvas.height);
&#13;
canvas#clock{
width:300px;
height:300px;
border:#D50003 1px solid;
background:#1E1E1E;
}
&#13;
<canvas id="clock" width="300" height="300"></canvas>
<div id="status"></div>
&#13;
让我们证明原始代码中的画布实际上是通过在其上画一个圆圈将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);
&#13;
canvas#clock {
width: 300px;
height: 300px;
border: #D50003 1px solid;
background: #1E1E1E;
}
&#13;
<canvas id="clock"></canvas>
<div id="status"></div>
&#13;
正如您所看到的,圆圈是扭曲的,因为我们使用画布的默认尺寸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);
&#13;
canvas#clock {
width: 300px;
height: 300px;
border: #D50003 1px solid;
background: #1E1E1E;
}
&#13;
<canvas id="clock" width="300" height="300"></canvas>
<div id="status"></div>
&#13;