I have a drawing pad, and I use quadraticCurveTo to make all of the lines and curves, and I want the line to get thinner when you move the mouse faster. However if I just do something like calculate the velocity of the pen and have that alter the thickness of the curves, then each curve is a different thickness, and the thickness doesn't change smoothly. Is there another way to do this?
In other words - can quadraticCurveTo only draw a curve at a set thickness, and not change the thickness throughout the curve?
If yes, can you think of another way I can change the thickness of the line?
Here is a jsfiddle:
Here is the main part of the code that draws the curves -
if (isMouseDown){
++i;
X[i] = e.pageX;
Y[i] = e.pageY;
var x1 = X[i-2];
var y1 = Y[i-2];
var x2 = X[i-1];
var y2 = Y[i-1];
var x3 = X[i];
var y3 = Y[i];
var mid1x = (x1 + x2)/2;
var mid1y = (y1 + y2)/2;
var mid2x = (x2 + x3)/2;
var mid2y = (y2 + y3)/2;
var distance = Math.pow((Math.pow(mid2x-x2,2) + Math.pow(mid2y-y2,2)),2) + Math.pow((Math.pow(x2-mid1x,2) + Math.pow(y2-mid1y,2)),2);
var velocity = distance/2;
if(i>1)
{
if (velocity<1)
{ drawQuadraticThreePoints("black", 10, mid1x, mid1y, x2, y2, mid2x, mid2y);
}
else
{ drawQuadraticThreePoints("black", 10/velocity, mid1x, mid1y, x2, y2, mid2x, mid2y);
}
}
}
function drawQuadraticThreePoints (color, thickness, x1,y1,x2,y2,x3,y3) {
context.strokeStyle = color;
context.lineWidth = thickness;
context.beginPath();
context.moveTo(x1,y1);
context.quadraticCurveTo(x2,y2,x3,y3);
context.stroke();
}
You only get 1 context.lineWidth setting for each context.beginPath.
That means your context.quadraticCurveTo can only have 1 linewidth.
To get a variable width line without the "chunky" width changes, you must break your quadratic curves into many smaller line-segments.
With many line-segements you can gradually change the line width between each segment.
The following function calculates xy points along a quadratic curve.
function getQuadraticBezierXYatT(startPt,controlPt,endPt,T) {
var x = Math.pow(1-T,2) * startPt.x + 2 * (1-T) * T * controlPt.x + Math.pow(T,2) * endPt.x;
var y = Math.pow(1-T,2) * startPt.y + 2 * (1-T) * T * controlPt.y + Math.pow(T,2) * endPt.y;
return( {x:x,y:y} );
}
These are the inputs to the function:
The rule of 1 lineWidth per beginPath still applies, but drawing multiple line segments per curve gives you more beginPaths with which to gradually adjust your lineWidth.