gokeekun2020
gokeekun2020

Reputation: 1

How to remove only one path from a canvas element

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

Answers (1)

Tags
Tags

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:

  • more robust: will work in all situations (even when objects overlap)
  • Scales well: better when lots of objects are painted

Cons:

  • every object has to be repainted on the canvas. (removes everything)

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:

  • Only removes the second path, leaves everything else
  • simpler when fewer objects are on the canvas

Cons:

  • Will not work when objects overlap.
  • Does not scale well: this solution will get more complex when more objects are being modified.

More resources:

Upvotes: 1

Related Questions