Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Javascript canvas drawLineDash to only one line

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!