Object.height returns half the height

I have a canvas whose height I am trying to get through JavaScript, but it returns half the height, not the actual height

Here is a simple code that I use

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>
Run codeHide result
+4
source share
1 answer

The width and height of the canvas are not set by CSS, they are set by the attributes widthand the heightcanvas. You see 150 because this is the default height. From MDN :

HTMLCanvasElement.height , HTML , CSS. , , 150.

CSS , . , , . , , , 300x150 ( ) , 300x300.

, CSS, getComputedStyle:

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);
canvas#clock{
	width:300px;
	height:300px;
	border:#D50003 1px solid;
	background:#1E1E1E;
}
<canvas id="clock" width="300" height="300"></canvas>
<div id="status"></div>
Hide result

, 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>
Hide result

, , 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>
Hide result
+5

Source: https://habr.com/ru/post/1610374/


All Articles