如何使用javascript从css属性(顶部、底部、左侧、右侧)计算框的宽度和高度



我用鼠标在画布上绘制了一个方框的上、下、左、右位置。我怎样才能计算出盒子的宽度和高度

您可以使用getBoundingClientRect()方法,该方法返回元素的大小及其相对于视口的位置。

此方法返回一个DOMReg对象,该对象具有八个属性:left、top、right、bottom、x、y、width、height

点击这里了解更多信息。

var canvas = document.querySelector("canvas");
var rect = canvas.getBoundingClientRect();
x = rect.left;
y = rect.top;
w = rect.width;
h = rect.height;
console.log("Left: " , x , ", Top: " , y , ", Width: " , w , ", Height: " , h);
canvas {
border:1px solid #d3d3d3;
background-color: #ff0000;
}
<canvas width="240" height="297">
Your browser does not support the HTML5 canvas tag.
</canvas>

最新更新