如何在缩放画布中获取像素范围?

在下面的代码中,我在中心画了一个圆,但是因为它是缩放的,所以这个圆在右下角!


var canvas = document.getElementById('mycanvas');

context = canvas.getContext("2d");

context.canvas.width = 400;

context.canvas.height = 200;


context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas


var scale = 2;

context.scale(scale, scale);

context.beginPath();

context.fillStyle = "#ff2626"; // Red color

context.arc(context.canvas.width / 2, context.canvas.height / 2, 10, 0, Math.PI * 2); //center

context.fill();

context.closePath();

canvas {

        border: solid 1px #ccc;

}

<HTML>

<body>


<canvas id="mycanvas"></canvas>


</body>

</HTML>

您可能知道,画布的宽度和高度与在其中绘制的内容无关,尤其是在缩放时。换句话说,当您使用context.scale(scale_x, scale_y);它缩放画布时,它将缩放画布内的所有形状。我想知道,有没有办法获得画布像素范围?

我想知道缩放画布时左边缘和右边缘的 X 以及顶部和底部边缘的 Y。


开满天机
浏览 151回答 3
3回答

RISEBY

将坐标除以scale应该可以解决问题:var canvas = document.getElementById('mycanvas');context = canvas.getContext("2d");context.canvas.width = 400;context.canvas.height = 200;context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvasvar scale = 2;context.scale(scale, scale);context.beginPath();context.fillStyle = "#ff2626"; // Red colorcontext.arc(context.canvas.width /2/scale, context.canvas.height / 2/scale, 10, 0, Math.PI * 2); //centercontext.fill();context.closePath();canvas {&nbsp; &nbsp; &nbsp; &nbsp; border: solid 1px #ccc;}<HTML><body><canvas id="mycanvas"></canvas></body></HTML>顺便说一句,context.canvas.width /(2*scale)比 更干净context.canvas.width /2/scale,但我保持这样只是为了显示除以scale.

冉冉说

你必须考虑你的比例所以 ex (width/2)/scalevar canvas = document.getElementById('mycanvas');context = canvas.getContext("2d");context.canvas.width = 400;context.canvas.height = 200;context.clearRect(context.canvas.width, context.canvas.height, context.canvas.width, context.canvas.height); // Clears the canvasvar scale = 2;context.scale(scale, scale);context.beginPath();context.fillStyle = "#ff2626"; // Red colorcontext.arc((context.canvas.width/2)/scale , (context.canvas.height/2)/scale, 10, 0, Math.PI * 2); //centercontext.fill();context.closePath();canvas {&nbsp; &nbsp; &nbsp; &nbsp; border: solid 1px #ccc;}<HTML><body><canvas id="mycanvas"></canvas></body></HTML>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript