In the live demo hereI 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 ?
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();
CodePudding user response:
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.
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.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.strokeStyle = 'grey';
// draw alle the lines
lines.forEach(line => {
context.moveTo(line.x1, line.y1);
context.lineTo(line.x2, line.y2);
});
context.stroke();
}
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>