Reputation: 3568
I have implemented line drawing in canvas
. But I faced a problem:
when line width is small (3), curved line looks nice;
when line width is large (20), curved line looks not good because of breaks.
canvas.node.onmousemove = function (e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
ctx.beginPath();
ctx.moveTo(canvas.lastX, canvas.lastY);
ctx.strokeStyle = '#000000';
ctx.lineWidth = self.lineWidth();
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
canvas.lastX = x;
canvas.lastY = y;
};
canvas.node.onmousedown = function (e) {
canvas.isDrawing = true;
canvas.lastX = e.pageX - this.offsetLeft;
canvas.lastY = e.pageY - this.offsetTop;
};
canvas.node.onmouseup = function (e) {
canvas.isDrawing = false;
};
How can I avoid breaks in large lines and make my line solid?
Thank you.
Upvotes: 1
Views: 532
Reputation: 3827
Have you tried setting the lineJoin
property to your canvas context?
Add the following line after you set your lineWidth
.
ctx.lineJoin = 'round';
This will not work if you have closed your path before completing rendering all the lineTo
's using ctx.closePath()
.
You will have to open the path before you start drawing the line and close it after you have finished drawing the line.
Also if you move the drawing cursor using moveTo
during drawing the lineJoin
doesn't come into play.
You can try the following modified code (I have also included a JSFiddle link in the end).
EDIT 1: Updated the code as I forgot to add the lineJoin
property to it.
EDIT 2: Moved the moveTo
line to the appropriate listener method.
canvas.node.onmousemove = function (e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
canvas.lastX = x;
canvas.lastY = y;
};
canvas.node.onmousedown = function (e) {
canvas.isDrawing = true;
canvas.lastX = e.pageX - this.offsetLeft;
canvas.lastY = e.pageY - this.offsetTop;
ctx.moveTo(canvas.lastX, canvas.lastY);
ctx.beginPath();
ctx.strokeStyle = '#000000';
ctx.lineWidth = self.lineWidth();
ctx.lineJoin = 'round';
};
canvas.node.onmouseup = function (e) {
ctx.closePath();
canvas.isDrawing = false;
};
Working JSFiddle here.
Upvotes: 2