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;
}
谢谢。
最佳答案
HTML5 Canvas 中的笔画(如 Adobe Illustrator 或 SVG 中一样)始终以它们所笔画的路径为中心。很久以前我proposed一个new SVG property这听起来像你想要的,但这个功能既不在 SVG 中,也不在 Canvas 中。 您的中风表现符合预期。
但是,您可以通过使用 clipping region 解决此问题 ,剪切到与您要描边的路径相同的位置,并将标称线宽加倍:
function clippedRectStroke( ctx, x, y, w, h ){
ctx.save();
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x,y+h);
ctx.lineTo(x+w,y+h);
ctx.lineTo(x+w,y);
ctx.clip();
ctx.lineWidth *= 2;
ctx.strokeRect(x,y,w,h);
ctx.restore();
};
这里的工作演示:http://jsfiddle.net/Dvz9Y/2/
关于html - 防止笔画边框溢出路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915031/