代码之家  ›  专栏  ›  技术社区  ›  Victoria

Mapbox地图上的抖动画布动画

  •  0
  • Victoria  · 技术社区  · 3 年前

    我正在尝试在Mapbox地图(Mapbox gl)上沿路线设置画布标记的动画。 但是画布动画看起来真的很不稳定,尤其是当动画很慢的时候。

    这是一个例子 https://codepen.io/vps-dev/pen/MWzqpRx

    画布图像创建:

    const canvasMarker = {
          width: size,
          height: size,
          data: new Uint8Array(size * size * 4),
          context: null,
    
          // When the layer is added to the map,
          // get the rendering context for the map canvas.
          onAdd: function () {
            const canvas = document.createElement('canvas')
            canvas.width = this.width
            canvas.height = this.height
            this.context = canvas.getContext('2d')
          },
    
          // Call once before every frame where the icon will be used.
          render: function () {
            const context = this.context
            if (!context) return false
    
            context.clearRect(0, 0, context.canvas.width, context.canvas.height)
            context.beginPath()
    
            context.font = '30px Arial'
            context.fillText('Hello World', 0, 20)
            context.rect(0, 40, this.width, 10)
            context.rect(0, 55, this.width, 10)
            context.fillStyle = '#000'
            context.fill()
    
            this.data = context.getImageData(0, 0, this.width, this.height).data
            
            map.triggerRepaint()
    
            // Return `true` to let the map know that the image was updated.
            return true
          },
        };
    

    正在地图上添加图像:

    map.addImage('canvas-marker', canvasMarker, { pixelRatio: 2 })
          
    map.addLayer({
     'id': 'point',
     'source': 'point',
     'type': 'symbol',
     'layout': {
       'icon-image': 'canvas-marker',
       'icon-size': 1.5,
        'icon-allow-overlap': true,
        'icon-ignore-placement': true
      }
    });
    

    然后使用requestAnimationFrame设置点的动画

    你能支持我吗?我做错了什么? 谢谢你的帮助!

    0 回复  |  直到 3 年前
        1
  •  1
  •   Steve Bennett    3 年前

    我认为你的问题是你在期待 requestAnimationFrame() 以精确均匀的间隔调用,但不会。

    您需要跟踪自上次动画更新以来的时间,然后按比例移动标记。例如,如果是5毫秒,你就移动5公里,如果是30毫秒,你就会移动30公里。

    您可以在这里的示例中看到这一点: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

    所以你的 animate() 函数应该使用传递给它的参数: animate(timeStamp) 然后使用它,而不是递增 counter .

    推荐文章