html5 canvas prevent linewidth scaling

2019-01-26 04:57发布

If I draw a rectangle of say linewidth=2 and then scale it to double the size of the rectangle, I get a rectangle that has its border double the size of the initial linewidth.

Is there a way to keep the linewidth to the perceived size of 2 or the original size.

In short, I want to just scale the size of the rectangle but keep the linewidth visually of size 2.

I tried setting the linewidth before and after the scale(2,2) command but the border width also increases.

One option is to divide the linewidth by the scale factor and this will work if the x and y scale factors are the same.

I don't have the option to scale the rectangle width and height and I need to use the scale command as I have other objects within the rectangle that need the scaling.

3条回答
成全新的幸福
2楼-- · 2019-01-26 05:21

The lineWidth should be scaled down beforehand.

ctx.lineWidth = 2 / Math.max(scaleX, scaleY);
ctx.scale(scaleX, scaleY);
ctx.fillRect(50, 50, 50, 50);
查看更多
迷人小祖宗
3楼-- · 2019-01-26 05:21

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);
查看更多
太酷不给撩
4楼-- · 2019-01-26 05:24

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

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
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
</script> 

</body>
</html>
查看更多
登录 后发表回答