【问题标题】:canvas translate path notworking画布翻译路径不起作用
【发布时间】:2022-11-13 12:20:09
【问题描述】:

我有一条在画布上画得很好的路径。

但我不能动它。

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

【问题讨论】:

    标签: javascript svg canvas 2d draw


    【解决方案1】:

    const ctx = canvas.getContext('2d')
    
    // reset the transform at the beginning
    ctx.resetTransform()
    
    const render = () => {
      // translate from last pos
      ctx.translate(1, 0)
    
      // clear ctx and then render what you want
      ctx.clearRect(0, 0, innerWidth, innerHeight)
      ctx.beginPath()
      ctx.moveTo(30, 50)
      ctx.lineTo(150, 100)
      ctx.strokeStyle = 'red'
      ctx.stroke();
    }
    
    // how many time beetwen two renders
    const interval = 25
    
    // How much we already rendered
    let done = 0
    
    const update = () => requestAnimationFrame(time => {
      let dt = time - done
    
      // update as many time as passed since last render
      while (dt >= interval) {
        dt -= interval
        done += interval
    
        render()
      }
    
      // recall the function so it works for the next frame
      update()
    })
    
    // call the first time to ignite 
    update()
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    
    <body>
      <canvas id="moving-canvas"></canvas>
    
      <script>
        const canvas = document.querySelector('#moving-canvas')
      </script>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 2018-09-28
      • 2014-05-02
      • 2019-10-16
      • 1970-01-01
      • 2019-01-16
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多