簡單使用 MapboxGL 自定義圖層繪製帶貼圖的矩形


寫文目的

不是經常用,可能會忘記基本用法,自留。

貼圖

image

效果

image

注意點

  • 構成矩形的兩個三角形需要使用 mapboxgl.MercatorCoordinate.fromLngLat 方法轉換至 WebGL 中的場景世界座標,注意案例中是如何設置三角形順序的,要逆時針
  • render 函數是每一幀繪製的調用函數,每一幀都要設置一次 program、texture、vertexBuffer,才能觸發 draw,並且尤爲注意矩陣 uniform 的地址,也是每一幀都要獲取最新的(gl.getUniformLocation(this.program, 'u_matrix')
  • 貼圖的長寬尺寸要用 2 的次冪

源碼

訪問令牌請使用自己的,代碼不做解釋,基本的註釋已完備。

頁面部分(省略,請自己補全):

<link href="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js"></script>
<style>
#map {
  width: 90vw;
  height: 90vh;
}
</style>
<div id="map"></div>

<script>
  // js 部分,見下
</script>

js 部分:

mapboxgl.accessToken = '你的令牌'

const map = new mapboxgl.Map({
  container: 'map',
  zoom: 7,
  center: [112.5, 22.5],
  style: 'mapbox://styles/mapbox/light-v10',
  // 開啓 WebGL 的 msaa(抗鋸齒)
  antialias: true
})

const vertexSource = /* glsl */`
uniform mat4 u_matrix;
attribute vec3 a_pos;
attribute vec2 a_uv;
varying vec2 v_uv;
void main() {
  v_uv = a_uv;
  gl_Position = u_matrix * vec4(a_pos, 1.0);
}`

const fragmentSource = /* glsl */`
precision mediump float;
varying vec2 v_uv;
uniform sampler2D u_sampler;
void main() {
    gl_FragColor = texture2D(u_sampler, v_uv);
}`

// create a custom style layer to implement the WebGL content
const customLayer = {
  id: 'highlight',
  type: 'custom',

  // 當圖層添加時調用的函數
  // https://docs.mapbox.com/mapbox-gl-js/api/#styleimageinterface#onadd
  onAdd: function (map, /** @type {WebGLRenderingContext} */gl) {

    // 創建、編譯頂點着色器
    const vertexShader = gl.createShader(gl.VERTEX_SHADER)
    gl.shaderSource(vertexShader, vertexSource)
    gl.compileShader(vertexShader)

    // 創建、編譯片元着色器
    const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
    gl.shaderSource(fragmentShader, fragmentSource)
    gl.compileShader(fragmentShader)

    // 創建着色器程序,鏈接片元和頂點着色器
    this.program = gl.createProgram()
    gl.attachShader(this.program, vertexShader)
    gl.attachShader(this.program, fragmentShader)
    gl.linkProgram(this.program)

    // 把 vertexAttributes 和 uniform 在着色器中的位置保存下來
    this.aPos = gl.getAttribLocation(this.program, 'a_pos')
    this.aUv = gl.getAttribLocation(this.program, 'a_uv')
    this.uSamplerLoc = gl.getUniformLocation(this.program, 'u_sampler')

    // 四個點用於定義一個矩形
    const p1 = mapboxgl.MercatorCoordinate.fromLngLat({
      lng: 112.5494384765625,
      lat: 22.268764039073968
    }, 10)
    const p2 = mapboxgl.MercatorCoordinate.fromLngLat({
      lng: 114.0216064453125,
      lat: 22.268764039073968
    }, 10)
    const p3 = mapboxgl.MercatorCoordinate.fromLngLat({
      lng: 114.0216064453125,
      lat: 23.28171917560002
    }, 10)
    const p4 = mapboxgl.MercatorCoordinate.fromLngLat({
      lng: 112.5494384765625,
      lat: 23.28171917560002
    }, 10)

    // 加載貼圖並創建紋理,在加載完畢的回調函數中上載貼圖數據
    const img = new Image()
    img.src = './img.png'
    this.texture = gl.createTexture()
    img.onload = () => {
      // bind 和 storei 操作必須等紋理解碼完成
      gl.bindTexture(gl.TEXTURE_2D, this.texture)
      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)

      // 上載數據
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)
    }

    // 創建 VBO
    this.buffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer)
    gl.bufferData(
      gl.ARRAY_BUFFER,
      new Float32Array([
        // position, uv
        p1.x, p1.y, p1.z, 0, 0,
        p2.x, p2.y, p2.z, 1, 0,
        p3.x, p3.y, p3.z, 1, 1,

        p1.x, p1.y, p1.z, 0, 0,
        p3.x, p3.y, p3.z, 1, 1,
        p4.x, p4.y, p4.z, 0, 1,
      ]),
      gl.STATIC_DRAW
    )
  },

  // 每幀運行
  // https://docs.mapbox.com/mapbox-gl-js/api/#map.event:render
  render: function (/** @type {WebGLRenderingContext} */gl, matrix) {
    // 每幀都要指定用哪個着色器程序
    gl.useProgram(this.program)
    // 每幀都要傳遞 uniform
    gl.uniformMatrix4fv(
      gl.getUniformLocation(this.program, 'u_matrix'),
      false,
      matrix
    )
    // 每幀都要綁定紋理參數
    gl.bindTexture(gl.TEXTURE_2D, this.texture)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)

    // 每幀都要綁定 VBO,並啓用 vertexAttributes、設置 vertexAttributes 的參數
    gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer)
    gl.enableVertexAttribArray(this.aPos)
    gl.enableVertexAttribArray(this.aUv)
    gl.vertexAttribPointer(this.aPos, 3, gl.FLOAT, false, 20, 0)
    gl.vertexAttribPointer(this.aUv, 2, gl.FLOAT, false, 20, 12)

    // 如果你用不着透明度,可以不執行這兩行
    // gl.enable(gl.BLEND)
    // gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

    // 觸發繪製
    gl.drawArrays(gl.TRIANGLES, 0, 6)
  }
}

map.on('load', () => {
  map.addLayer(customLayer)
})

可改進點

上述例子在添加進 map 之後,圖片還是沒有請求、解碼完成的,其回調函數還沒有執行,如果你不去動一下地圖,比如點擊一下或移動一下視角,是不會更新的,有可能是黑黑的一個框 —— 紋理還沒準備好,只能畫黑框框。

改進方法也很簡單,可以先在自定義圖層之外異步請求完成圖片、解碼(Image 支持返回 Promise 的 decode 方法),再將 customLayer 對象創建、添加到地圖中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章