skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 with ctx.beginPath():

    var c = document.getElementById("chartCanvas");
    var ctx = c.getContext("2d");
    let userInput = document.getElementById("userInput");
    
    function drawIndexLine(index) {
      ctx.clearRect(0, 0, c.width, c.height);
      ctx.beginPath();
      ctx.moveTo(index, 0);
      ctx.lineTo(index, 150);
      ctx.stroke();
    }
    
    userInput.addEventListener('input', function() {
      let value = Number(this.value);
      drawIndexLine(value);
    })
    canvas {
      border: solid;
    }
    <p>enter number <input id="userInput" type="number"></p>
    <canvas id="chartCanvas"></canvas>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search