Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda