防止笔画边框溢出路径
planetRect(0, 0, canvasWidth, canvasHeight);
绘制一个完整的矩形,但线宽减半,这里是一个例子:
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName ("canvas");
var lineWidth = 10;
var canvasHeight = canvas[0].height;
var canvasWidth = canvas[0].width;
var ctx = canvas[0].getContext ("2d");
ctx.lineWidth = lineWidth;
ctx.strokeRect (0, 0, canvasWidth, canvasHeight);
</script>
我可以解决这个问题,但并不优雅:
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName ("canvas");
var lineWidth = 10;
var canvasHeight = canvas[0].height - lineWidth;
var canvasWidth = canvas[0].width - lineWidth;
var ctx = canvas[0].getContext ("2d");
ctx.lineWidth = lineWidth;
lineWidth /= 2;
ctx.strokeRect (lineWidth, lineWidth, canvasWidth, canvasHeight);
</script>
有没有一种本地方法可以做到这一点?像“box-sizing”css3 属性之类的东西:
canvas {
box-sizing: border-box;
}
谢谢。
strokeRect (0, 0, canvasWidth, canvasHeight);
draws a full rectangle but the line width is cut in half, here is an example:
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName ("canvas");
var lineWidth = 10;
var canvasHeight = canvas[0].height;
var canvasWidth = canvas[0].width;
var ctx = canvas[0].getContext ("2d");
ctx.lineWidth = lineWidth;
ctx.strokeRect (0, 0, canvasWidth, canvasHeight);
</script>
I can fix that but isn't elegant:
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName ("canvas");
var lineWidth = 10;
var canvasHeight = canvas[0].height - lineWidth;
var canvasWidth = canvas[0].width - lineWidth;
var ctx = canvas[0].getContext ("2d");
ctx.lineWidth = lineWidth;
lineWidth /= 2;
ctx.strokeRect (lineWidth, lineWidth, canvasWidth, canvasHeight);
</script>
Is there a native method to do that ? Something like the "box-sizing" css3 attribute:
canvas {
box-sizing: border-box;
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HTML5 Canvas 中的笔画(如 Adobe Illustrator 或 SVG 中一样)始终以它们所描画的路径为中心。很久以前,我提议新的 SVG 属性 听起来像您想要的,但此功能既不在 SVG 中,也不在 Canvas 中。 您的中风表现符合预期。
但是,您可以使用 剪切区域,剪切到与您要描边的路径相同的位置,并将您的标称线宽:
此处工作演示:http://jsfiddle.net/Dvz9Y/2/
Strokes in HTML5 Canvas—as in Adobe Illustrator or SVG—are always centered on the path that they are stroking. Long ago I proposed a new SVG property that sounds like what you want, but this functionality is in neither SVG nor Canvas. Your stroke is behaving as it is supposed to.
However, you can work around this by using clipping region, clipping to the same as the path you are about to stroke and doubling your nominal lineWidth:
Working demo here: http://jsfiddle.net/Dvz9Y/2/