为什么描边的矩形往往会超出画布的范围?

时间:2018-11-21 00:00:32

标签: javascript canvas

我最近一直在试验 ,在笔触靠近原点的矩形 (0,0)<时,我注意到一个奇怪的行为。 / strong>。

// canvas context
var ctx = document.querySelector('#screen').getContext('2d');

// draw a rectangle
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);

// stroke a border for the rectangle
ctx.lineWidth = 20;
ctx.strokeRect(0, 0, 100, 100);
<canvas id="screen"></canvas>

出了什么问题?

在上面的示例中,矩形本身是按预期在(0,0)处绘制的,但是其边框(描边的矩形)似乎是以偏移量绘制的。
< br /> 通常,在远离原点的位置抚摸矩形时,会忽略此效果- 我想这并不是说要从指定位置开始绘制描边的矩形,而是要从偏移位置开始绘制。

为什么?

1 个答案:

答案 0 :(得分:4)

笔划以原始图元定义的坐标为中心。对于笔划宽度为20的矩形,在画布的左上方绘制该矩形将导致一半的笔划宽度被绘制在画布边界之外。

strokeRect()的坐标调整为10,10,..会使矩形从画布原点偏移,这意味着20像素的整个笔画将从其左上角可见画布:

ctx.lineWidth = 20;
ctx.strokeRect(10, 10, 100, 100);

请考虑以下调整,以确保笔划在绘制的矩形周围完全可见:

var canvas = document.querySelector('#screen');

// Set the width and height to specify dimensions of canvas (in pixels)
// Choosing a 100x100 square matches the strokeRect() drawn below and
// therefore achieves the appearance of a symmetric stroke    
canvas.width = 100;
canvas.height = 100;

// canvas context
var ctx = canvas.getContext('2d');

// draw a rectangle
ctx.fillStyle = 'orange';
ctx.fillRect(10, 10, 90, 90);

// stroke a border for the rectangle
ctx.lineWidth = 20;

var halfStroke = ctx.lineWidth * 0.5;

ctx.strokeRect(halfStroke, halfStroke, 100 - (halfStroke * 2), 100 - (halfStroke * 2));
<canvas id="screen"></canvas>

更新

以下是与Ibrahim Mahrir提供的线/矩形边缘有关的笔画的可视化视图:

enter image description here