Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line thickness in a canvas element

Tags:

html

canvas

I want to make lines with a thickness of 1px in a canvas element.

I can't seem to find an example that is correct though. I am currently using the method on this site https://developer.mozilla.org/samples/canvas-tutorial/4_5_canvas_linewidth.html

In this example the line that should be 1px appears to actually be 2px but a lighter color. This is in both Chrome 10 and Firefox 4.

I would expect the width of that left most line to be the same as the one that is underlining the title on that page.

Is there another way to draw a line to get the results I am looking for.

like image 638
Mike Avatar asked Apr 15 '11 15:04

Mike


2 Answers

Notice the part

However, the leftmost and all other odd-integer-width thickness lines do not appear crisp, because of the path's positioning.

and

Obtaining crisp lines requires understanding how paths are stroked. In the images below, the grid represents the canvas coordinate grid. The squares between gridlines are actual on-screen pixels. In the first grid image below, a rectangle from (2,1) to (5,5) is filled. The entire area between them (light red) falls on pixel boundaries, so the resulting filled rectangle will have crisp edges.

So, if you draw at half pixels (when drawing an odd pixel width line) then the actual drawn edges will fall on absolute pixels and look fine..

example at http://jsfiddle.net/Wav5v/


Alternatively you can use the fillRect(x,y,width,height) with a width of 1..

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  for (i=0;i<10;i++){
    ctx.fillRect(5 + i*14, 5, 1+i, 140); 
  }
}

example at http://jsfiddle.net/Wav5v/1/

like image 180
Gabriele Petrioli Avatar answered Nov 02 '22 23:11

Gabriele Petrioli


I encountered the same problem: all my lines were much larger than 1 px

Here is what I had before my solution:

<canvas id="myCanvas"/>
<style type="text/css">
    #myCanvas {
        position: absolute;
        top:0px;
        width:1024px;
        height: 301px;
        background: transparent;
        border: 1px solid #FFF;
        }​
</style>

Using CSS to set the canvas size. My solution was to set the width and height of the canvas element in the html.

<canvas id="myCanvas" width=1024 height=301>

and then all was OK.

like image 45
Bryan Avatar answered Nov 03 '22 00:11

Bryan