Последовательное рисование линий
Всем доброго времени суток, возникла проблема с рисованием линий, код следующий:
let ctx = document.getElementById("canvas").getContext("2d");
DrawPoint(ctx, 50);
function DrawPoint(ctx, size) {
DrawSerif(ctx, ctx.canvas.width / 2, ctx.canvas.height / 2)
DrawSerif(ctx, ctx.canvas.width / 2 + size, ctx.canvas.height / 2)
DrawSerif(ctx, ctx.canvas.width / 2 + 2 * size, ctx.canvas.height / 2)
}
function DrawSerif(ctx, x, y) {
ctx.beginPath()
ctx.fillStyle = "red";
ctx.moveTo(x, y + 5)
ctx.lineTo(x, y - 5)
ctx.fill();
}
<canvas id="canvas" style="background: #ddd;"></canvas>
Проблема в том, что рисуется только последняя вызванная функция DrawSerif, может кто-то подсказать как избежать затирания предыдущих засечек?
Ответы (1 шт):
Автор решения: Grundy
→ Ссылка
метод fill закрашивает область, ограниченную контуром.
В данном случае контур не замкнут, поэтому и закрашивать нечего.
Если нужно закрасить линию (границу контура) - стоит использовать stroke
let ctx = document.getElementById("canvas").getContext("2d");
DrawPoint(ctx, 50);
function DrawPoint(ctx, size) {
DrawSerif(ctx, ctx.canvas.width / 2, ctx.canvas.height / 2)
DrawSerif(ctx, ctx.canvas.width / 2 + size, ctx.canvas.height / 2)
DrawSerif(ctx, ctx.canvas.width / 2 + 2 * size, ctx.canvas.height / 2)
}
function DrawSerif(ctx, x, y) {
ctx.beginPath()
ctx.strokeStyle = "red";
ctx.moveTo(x, y + 5)
ctx.lineTo(x, y - 5)
ctx.stroke();
}
<canvas id="canvas" style="background: #ddd;"></canvas>