html5画布阻止线宽缩放

问题描述 投票:15回答:3

如果我绘制一个说linewidth = 2的矩形,然后将其缩放为矩形的两倍,我得到一个矩形,其边框是初始线宽的两倍。

有没有办法将线宽保持为感知大小2或原始大小。

简而言之,我只想缩放矩形的大小,但在视觉上保持大小为2的线宽。

我尝试在scale(2,2)命令之前和之后设置线宽,但边框宽度也增加了。

一种选择是将线宽除以比例因子,如果x和y比例因子相同,这将起作用。

我没有缩放矩形宽度和高度的选项,我需要使用缩放命令,因为我需要缩放的矩形中有其他对象。

html5 canvas scaling
3个回答
19
投票

您可以使用转换定义路径并在没有转换的情况下将其描这样就不会改变线宽。

例:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save(); //save context without transformation
ctx.scale(2, 0.5); //make transformation
ctx.beginPath(); //define path
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.restore(); //restore context without transformation
ctx.stroke(); //stroke path
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">

6
投票

lineWidth应该预先缩小。

ctx.lineWidth = 2 / Math.max(scaleX, scaleY);
ctx.scale(scaleX, scaleY);
ctx.fillRect(50, 50, 50, 50);

1
投票

好的,你有几个选择:

您可以自己缩放坐标和尺寸,例如

ctx.strokeRect( scaleX * x, scaleY * y, scaleX * width, scaleY * height) ;

而且您还需要将缩放应用于所有其他对象。

或者,您可以应用缩放但不依赖于lineWidth来绘制矩形的边框。一个简单的方法是通过填充正确的区域绘制矩形,然后删除内部,减去边框,如下所示:

var scaleX = 1.5, scaleY = 2;
var lineWidth = 2;

ctx.scale(scaleX, scaleY);

ctx.fillStyle = "#000";
ctx.fillRect(100, 50, 100, 
ctx.clearRect(100+lineWidth/scaleX, 50+lineWidth/scaleY, 100-(2*lineWidth)/scaleX, 60-(2*lineWidth)/scaleY);
© www.soinside.com 2019 - 2024. All rights reserved.