HTML Canvas: как рисовать линии с помощью JavaScript

Чтобы нарисовать линию на холсте HTML, вы можете использовать следующие методы:

  1. Использование методов beginPath(), moveTo()и lineTo():

    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    context.beginPath();
    context.moveTo(x1, y1); // Starting point coordinates
    context.lineTo(x2, y2); // Ending point coordinates
    context.stroke();
  2. Непосредственное использование метода lineTo():

    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    context.moveTo(x1, y1); // Starting point coordinates
    context.lineTo(x2, y2); // Ending point coordinates
    context.stroke();
  3. Использование методов moveTo()и lineTo()с несколькими строками:

    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    context.moveTo(x1, y1); // Starting point coordinates for the first line
    context.lineTo(x2, y2); // Ending point coordinates for the first line
    context.moveTo(x3, y3); // Starting point coordinates for the second line
    context.lineTo(x4, y4); // Ending point coordinates for the second line
    context.stroke();