Smooth jagged lines drawn by user in HTML5 canvas app?

We have an HTML5 drawing application where users can draw lines with a pencil tool.

Compared to flash-based applications, the lines have slightly jagged edges and appear somewhat blurry. This is because users need to maintain a straight line while drawing, or the algorithm recognizes each pixel deviation and designs it as a jagged edge.

Drawing smooth, sharp circles as a result is not possible.

Be that as it may, other drawing applications can smooth out these jagged edges, allowing users to draw lines (straight or not).

Is there any way to smooth these lines?

Demo (select the pencil tool): http://devfiles.myopera.com/articles/649/example5.html

Our application uses a similar code.

+6
source share
3 answers

Here is an example of a quick way to use quadratic curves and the "round" lineJoin :

http://jsfiddle.net/NWBV4/10/

+7
source

Regarding strings or vectors .. this post is what you want

Drawing "GOOD WATCH" (like in Flash) on canvas (HTML5) - is it possible?

TL DR uses SVG

where ctx is the context

 ctx.lineCap = "round" 

then for drawing

 ctx.beginPath(); ctx.moveTo(data.line.startX,data.line.startY); ctx.lineTo(data.line.endX, data.line.endY); ctx.strokeStyle = data.line.color; ctx.stroke(); 

evidence

http://gentle-leaf-5790.herokuapp.com/

+5
source

You might want to keep the minimum length on the line drawn. To do this, take the pencil section of this example code and change it to something like this:

  tools.pencil = function () { var tool = this; // variables for last x, y and min_length of line var lx; var ly; var min_length = 3; this.started = false; // This is called when you start holding down the mouse button. // This starts the pencil drawing. this.mousedown = function (ev) { context.beginPath(); context.moveTo(ev._x, ev._y); tool.started = true; // update last x,y coordinates lx = ev._x; ly = ev._y; }; // This function is called every time you move the mouse. Obviously, it only // draws if the tool.started state is set to true (when you are holding down // the mouse button). this.mousemove = function (ev) { if (tool.started && (Math.sqrt(Math.pow(lx - ev._x, 2) + Math.pow(ly - ev._y, 2)) > min_length)) { context.lineTo(ev._x, ev._y); context.stroke(); lx = ev._x; ly = ev._y; } }; // This is called when you release the mouse button. this.mouseup = function (ev) { if (tool.started) { tool.mousemove(ev); tool.started = false; img_update(); } }; }; 
0
source

Source: https://habr.com/ru/post/911786/


All Articles