Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clearing a canvas before drawing a new line

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

var canvas = document.getElementById("chartCanvas");
var ctx = canvas.getContext("2d");
let userInput = document.getElementById("userInput");

function drawIndexLine(index) {
  ctx.canvas.width = ctx.canvas.width;
  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>

Also, just as a side note, these lines are vertical not horizontal.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading