admin管理员组

文章数量:1322838

A stupid simple canvas usage:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.strokeStyle = "#CCCC00";
ctx.lineWidth = 3;
ctx.strokeRect(0, 0, width, height);

Yields a rectangle with narrower lines along top and left:

Why does this happen? Do I need to offset with padding? It's annoying.

A stupid simple canvas usage:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.strokeStyle = "#CCCC00";
ctx.lineWidth = 3;
ctx.strokeRect(0, 0, width, height);

Yields a rectangle with narrower lines along top and left:

Why does this happen? Do I need to offset with padding? It's annoying.

Share Improve this question edited Aug 25, 2021 at 3:33 Alex Wayne 187k52 gold badges323 silver badges356 bronze badges asked Apr 4, 2012 at 0:44 WellsWells 11k16 gold badges57 silver badges91 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 31

2 things.

First, odd lineWidths (1, 3, 5, ...) will never apply cleanly with drawn on integer pixel values. This is because X and Y refer to the space between pixels rather than their centers. So a stroke of 1 that runs from [1,1] to [1,10] spills half into the pixel on the left column of pixels and half into right. If you instead draw that line from [1.5,1] to [1.5,10] then it fills half to the left, and half to the right, filling up the whole pixel column perfectly.

Any odd number width will show this behavior, but even numbers will not because they fill a full pixel on each side looking clean.


Second, the box is obscured by the top of the canvas. When you center your 3px stroke on [0,0] it spills as far up and left as [-1.5,-1.5] which is outside of the visible range of the canvas. So it appears half as thick as it should be.


See the proof of difference here:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// original box, eclipsed by canvas bounds
ctx.strokeStyle = "#CC0000";
ctx.lineWidth = 3;
ctx.strokeRect(0, 0, 20, 20);

// moved from canvas bounds
ctx.strokeStyle = "#CC0000";
ctx.lineWidth = 3;
ctx.strokeRect(25, 25, 20, 20);

// drawn on half pixel coordinates to prevent blurry lines with odd integer line widths.
ctx.strokeStyle = "#CC0000";
ctx.lineWidth = 3;
ctx.strokeRect(50.5, 50.5, 20, 20);
body { margin: 10px }
<canvas id="canvas" width="100" height="100"></canvas>

Which should render this:

The first one is like your code. The second is moved away from the top left edge to show its uniform in width. And the third shows how to render a 3px stroke without subpixel blurring.

Because you told it to draw a line with the width of 3 at 0... so 1/3rd of it is going to be off your canvas...

http://jsfiddle.net/mhFLG/ vs http://jsfiddle.net/mhFLG/1/

本文标签: javascriptHTML5canvasand strokeRect some lines too narrow and blurryStack Overflow