Search code examples
javascriptcanvas

canvas translate path notworking


I have a path that I draw well on the canvas.

But I can't move it.

    const ctx = canvas.getContext('2d')
    const render = () => {
        ctx.resetTransform()
        ctx.clearRect(0, 0, innerWidth, innerHeight)
        ctx.beginPath()
        ctx.moveTo(30, 50)
        ctx.lineTo(150, 100)
        ctx.translate(1000,100) // not working
        ctx.strokeStyle = 'red'
        ctx.stroke();
    }
    render()

Solution

  • You can use path2D and DOMMatrix.

    const canvas = document.createElement('canvas')
    
    document.body.appendChild(canvas)
    const ctx = canvas.getContext('2d')
    
    let pathX = 0
    let p1, p2
    const render = () => {
    ctx.clearRect(0, 0, innerWidth, innerHeight)
    
    //static path
    p1 = new Path2D()
    p1.moveTo(30, 50)
    p1.lineTo(150, 100)
    p2 = new Path2D()
    p2.addPath(p1, new DOMMatrix().rotate(-15))
    ctx.strokeStyle = 'green'
    ctx.stroke(p2)
    
    //dynamic path
    p1 = new Path2D()
    p1.moveTo(30, 50)
    p1.lineTo(150, 100)
    p2 = new Path2D()
    p2.addPath(p1, new DOMMatrix().translate(pathX++, 0))
    ctx.strokeStyle = 'red'
    ctx.stroke(p2)
    
    requestAnimationFrame(render)
    }
    render()

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    
    <body>
    </body>
    
    </html>