'Delete a HTML canvas Line

In the live demo here I have a grid here and I draw a ctx line on the grid. May I know how to remove the ctx line using a button?

My Canvas Here

In my JS code,

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(300, 150);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(350, 110);
ctx.stroke();


Solution 1:[1]

You cannot remove a line (or any other shape) from the canvas, but you can re-draw the entire thing. You then need to be able to maintain the "state" of the canvas. In this example I have an array of objects that represent individual lines. When the draw() function is called, the lines are also drawn on the canvas.

There are two functions to illustrate how you can change the state by removing lines or adding new lines. So, depending on how the user should interact with the canvas you would add and remove these lines/objects from the array.

Update

The style of the line can be changed using strokeStyle and lineWidth. These are applied on stroke(). For each stroke you need to stat a new path with beginPath(). In the beginnig and end of draw() I added save() and restore(). save() saves the current state (kind of the initial state, here) and restore() reverts back to that state.

var lines = [{
    x1: 0,
    y1: 0,
    x2: 300,
    y2: 110
  },
  {
    x1: 10,
    y1: 10,
    x2: 350,
    y2: 110
  }
];
var canvas, context;

canvas = document.getElementById('canvas');
if (canvas.getContext) {
  context = canvas.getContext('2d');
  draw(); // intitial draw
}

function draw() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.save();
  context.strokeStyle = 'grey';
  context.beginPath();
  for (var x = 0.5; x < 500; x += 50) {
    context.moveTo(x, 0);
    context.lineTo(x, 500);
  }
  for (var y = 0.5; y < 500; y += 50) {
    context.moveTo(0, y);
    context.lineTo(500, y);
  }
  context.stroke();
  context.strokeStyle = 'red';
  context.lineWidth = 3;
  context.beginPath();
  // draw alle the lines
  lines.forEach(line => {
    context.moveTo(line.x1, line.y1);
    context.lineTo(line.x2, line.y2);
  });
  context.stroke();
  context.restore();
}

function removeline(){
  lines.shift();
  draw(); // re-draw the canvas
}

function addline(){
  let line = {
    x1: Math.random()*500,
    y1: Math.random()*500,
    x2: Math.random()*500,
    y2: Math.random()*500
  };
  lines.push(line);
  draw(); // re-draw the canvas
}
<div>
  <button onclick="removeline()">Remove line</button>
  <button onclick="addline()">Add line</button>
</div>
<canvas id='canvas' width="500" height="500"></canvas>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1