HTML5 Canvas: Smooth, variable width lines with transparency.

When making a drawing app with HTML5 canvas, you might come up against the problem of making a smooth, variable width line. Eventually you might find that you can make several calls to ctx.quadraticCurveTo(x,y,xc,yc) and get some kind of effect. If you stroke every 2 or 3 points, then as long as the line width is very small, you won’t notice the jaggedness.

Unfortunately, if you try to do this with semi-transparent lines, the effect is truly horrible. To solve this problem, instead of drawing lines, I simply draw very thin shapes, and fill them with a color. This allows for 1) variable thickness and 2) nice transparency. Variable transparency is a problem I haven’t quite figured out yet. It may require composing the shape from individual pixels, which is simply too slow, especially in IE.

What I am writing is a drawing App that works with the Wacom Web Plugin, and therefore varies line thickness based on pressure. I would like to vary opacity too, but this seems problematic right now. A solution that may be possible is to fill the shape with a complex gradient, if it is possible to create semi-transparent stops.

Here is an image of what the program does so far:

test

 

Each line is actually a full shape, with varying degrees of opacity. Thickness and thinness is accomplished with pen pressure from the Wacom Intuous5 tablet.

As the line is drawn, a temporary line is shown to the user, when they lift the pen, that line disappears, and a full rendering of it is done as a shape instead of a line. This is slower, but necessary for simplicity. This is meant to be a quick and easy sketch program for increasing your visual library and practicing gesture drawing.

As the person draws, the points are collected up into an array of vector objects which store the x,y, and pressure of the pen at the time that point was hit. The rendering function is like this:

The second part is thanks to my father, a mathematician and physicist who helped me figure out how to calculate the points directly. Math is something I am currently working on.

His “equation” as I call it, goes something like this:

jadczyk_line_eq1

I wouldn’t have been able to come up with this on my own.

About Jason

I am a 31 year old programmer living in the south of France. I currently work actively in the fields of Ruby/PHP/Javascript and server/website administration.
This entry was posted in Computer Science, HTML5, HTML5 Canvas, Javascript Tutorials, Tips and Tricks, Topics, Tutorials, Web Design and tagged , , , , , , . Bookmark the permalink.
  • el Luar

    any sample of this?

    • jasonrouge

      All the code and maybe working example is here: https://github.com/jasonknight/jwacom

      I gave up on the idea because the web plugin support for wacom is basically non-existent.