Reputation: 1
I want to either remove, change the colour of or change the position of the second line.
Also, is there a way to make the colour of an already created line different?
var cvs = document.querySelector('#canvas')
var ctx = cvs.getContext('2d')
cvs.height = window.innerHeight - 40
cvs.width = window.innerWidth - 40
window.addEventListener('resize', () => {
cvs.height = window.innerHeight - 40;
cvs.width = window.innerWidth - 40;
})
ctx.beginPath();
ctx.strokeStyle = 'red'
ctx.lineWidth = '5'
ctx.lineCap = 'round'
ctx.moveTo(200, 600)
ctx.lineto(100,100)
ctx.closePath();
//Second path which is what i want to remove only
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.lineWidth = '37px'
ctx.moveTo(100,100)
ctx.lineTo(300, 500)
ctx.stroke()
ctx.closePath()
Upvotes: 0
Views: 951
Reputation: 46
Objects painted on the canvas cannot be modified, but they can be painted over. Unlike HTML or SVG, the the canvas does not have its own DOM, so there is no way to access objects that have already painted on the canvas.
Approach 1:
The most common approach is to clear the canvas, adjust any attributes (position, color, etc), and repaint the objects onto the canvas.
ctx.clearRect(0, 0, cvs.width, cvs.height) //removes everything from the canvas
ctx.beginPath();
ctx.strokeStyle = 'red'
ctx.lineWidth = '5'
ctx.lineCap = 'round'
ctx.moveTo(200, 600)
ctx.lineTo(100,100)
ctx.stroke();
ctx.closePath(); //repaints the first object, the second path is gone.
Pros:
Cons:
Approach 2:
The closest approach to removing a single object, it paints over the existing object and repaint it somewhere else.
ctx.beginPath();
ctx.strokeStyle = 'white' //background color
ctx.lineWidth = '37px'
ctx.moveTo(100,100);
ctx.lineTo(300, 500);
ctx.stroke();
ctx.closePath(); // covers up the second path
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.lineWidth = '37px'
ctx.moveTo(100,100)
ctx.lineTo(600, 500) //repaint this object somewhere else
ctx.stroke()
ctx.closePath()
Pros:
Cons:
More resources:
Upvotes: 1