【问题标题】:How to remove only one path from a canvas element如何从画布元素中仅删除一条路径
【发布时间】:2026-01-08 03:50:01
【问题描述】:

我想删除、更改第二行的颜色或更改第二行的位置。

另外,有没有办法使已经创建的线条的颜色不同?

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()

【问题讨论】:

    标签: javascript html canvas path


    【解决方案1】:

    在画布上绘制的对象无法修改,但可以覆盖。与 HTML 或 SVG 不同,画布没有自己的 DOM,因此无法访问已在画布上绘制的对象。

    方法一:

    最常见的方法是清除画布,调整任何属性(位置、颜色等),然后在画布上重新绘制对象

    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.
    

    优点:

    • 更健壮:适用于所有情况(即使对象重叠)
    • 缩放良好:绘制大量对象时效果更好

    缺点:

    • 必须在画布上重新绘制每个对象。 (删除所有内容)

    方法2:

    最接近移除单个对象的方法,它在现有对象上绘制,然后在其他地方重新绘制

    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()
    

    优点:

    • 仅删除第二条路径,保留其他所有路径
    • 当画布上的对象越少时越简单

    缺点:

    • 当对象重叠时将不起作用
    • 不能很好地扩展:当修改更多对象时,此解决方案会变得更加复杂。

    更多资源:

    【讨论】: