html5 canvas prevent linewidth scaling

倾然丶 夕夏残阳落幕 提交于 2019-12-01 02:32:59
Milan Bydžovský

You can define path with transformation and stroke it without one. That way line width won't be transformed.

Example:

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;">
naka

The lineWidth should be scaled down beforehand.

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

Ok, you have a couple of options:

You can do your own scaling of coordinates and dimensions, e.g.

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

And you'll need to apply the scaling to all the other objects too.

Alternatively you could apply the scaling but not rely on lineWidth for drawing the border of the rectangle. A simple method would be to draw the rectangle by filling the correct region and then removing the interior, minus the border, like so:

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!