I have a chart in canvas form and I want to draw a horizontal line when the user enters a number in my form.
Each time the user enters a new number a new line is drawn and the old one is still shown. I need to only show one line at a time. How can I do this?
var c = document.getElementById("chartCanvas");
var ctx = c.getContext("2d");
let userInput = document.getElementById("userInput");
function drawIndexLine(index) {
ctx.moveTo(index, 0);
ctx.lineTo(index, 150);
ctx.stroke();
}
userInput.addEventListener('change', function() {
let value = Number(this.value);
drawIndexLine(value);
})
canvas {
border: solid;
}
<p>enter number <input id="userInput" type="number"></p>
<canvas id="chartCanvas"></canvas>
2
Answers
A quick and easy way to clear a canvas is to update at least one of its dimensions – even to the same size. Note that there are caveats to this (such as it potentially resetting stroke and fill settings), but they are not an issue for the use case presented here.
Here’s a working example:
Also, just as a side note, these lines are vertical not horizontal.
Do not use the
canvas.width
setter hack from the other answer this will reset all the properties of your canvas context, AND reset its bitmap buffer, which is not only super slow, but super memory inefficient.Instead clear your canvas buffer (without replacing it) with
ctx.clearRect()
and start a new path withctx.beginPath()
: