On my application I have to draw separate lines. One line solid and one line dashed. I am using the CanvasRenderingContext2D. My problem is how can I draw one dotted line and one solid line using the same context. What I have tried is:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.setLineDash([2, 2])
ctx.moveTo(50, 50); // Begin first sub-path
ctx.lineTo(200, 50);
ctx.moveTo(50, 90); // Begin second sub-path
ctx.lineTo(280, 120);
ctx.stroke();
But it draws lines as dotted. It makes sense why, because I am using the same context for both lines but I need to use the same context in my app. I just gave a minimal example. Is there a way to do this?
In a canvas I would recommend to use some sort of prototype to represent a point in your coordinate system. Then you can simply pass the points to your drawLine function and pass an additional style.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function Point(x, y) {
this.x = x;
this.y = y;
}
function drawLine(from, to, style=[]) {
ctx.beginPath();
ctx.setLineDash(style)
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
ctx.closePath();
}
drawLine(new Point(50, 50), new Point(200, 50)); // solid line
drawLine(new Point(50, 90), new Point(280, 120), [2,2]); // dashed line
<canvas id="canvas" width="500" height="500"></canvas>