MapLibre GL JS第29课:添加Canvas源

📌 学习目标

  • 掌握添加Canvas源的实现方法
  • 理解相关API的使用
  • 能够独立完成类似功能开发

🎯 核心概念

向地图添加Canvas数据源。

💻 完 整 代 码

代码示例

js 复制代码
//Animation from https://javascript.tutorials24x7.com/blog/how-to-draw-animated-circles-in-html5-canvas
const canvas = document.getElementById('canvasID');
const ctx = canvas.getContext('2d');
canvas.style.display = 'none';
const circles = [];
const radius = 20;

function Circle(x, y, dx, dy, radius, color) {
    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;

    this.radius = radius;

    this.draw = function () {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        ctx.strokeStyle = color;
        ctx.stroke();
    };

    this.update = function () {
        if (this.x + this.radius > 400 || this.x - this.radius < 0) {
            this.dx = -this.dx;
        }

        if (this.y + this.radius > 400 || this.y - this.radius < 0) {
            this.dy = -this.dy;
        }

        this.x += this.dx;
        this.y += this.dy;

        this.draw();
    };
}

for (let i = 0; i < 5; i++) {
    const color = `#${(0x1000000 + Math.random() * 0xffffff).toString(16).substr(1, 6)}`;
    const x = Math.random() * (400 - radius * 2) + radius;
    const y = Math.random() * (400 - radius * 2) + radius;

    const dx = (Math.random() - 0.5) * 2;
    const dy = (Math.random() - 0.5) * 2;

    circles.push(new Circle(x, y, dx, dy, radius, color));
}

function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, 400, 400);

    for (let r = 0; r < 5; r++) {
        circles[r].update();
    }
}

animate();

const map = new maplibregl.Map({
    container: 'map',
    zoom: 5,
    minZoom: 4,
    center: [95.899147, 18.088694],
    style: 'https://demotiles.maplibre.org/style.json'
});

map.on('load', () => {
    map.addSource('canvas-source', {
        type: 'canvas',
        canvas: 'canvasID',
        coordinates: [
            [91.4461, 21.5006],
            [100.3541, 21.5006],
            [100.3541, 13.9706],
            [91.4461, 13.9706]
        ],
        // 如果Canvas源是动画的,设置为true。如果Canvas是静态的,设置为false以提高性能。
        animate: true
    });

    map.addLayer({
        id: 'canvas-layer',
        type: 'raster',
        source: 'canvas-source'
    });
});

代码示例

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Add a canvas source</title>
    <meta property="og:description" content="向地图添加画布源。" />
    <meta property="og:created" content="2025-06-25" />
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.css' />
    <script src='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.js'></script>
    <style>
        body { margin: 0; padding: 0; }
        html, body, #map { height: 100%; }
    </style>
</head>
<body>
<canvas id="canvasID" width="400" height="400">Canvas not supported</canvas>
<div id="map"></div>
<script>
    //Animation from https://javascript.tutorials24x7.com/blog/how-to-draw-animated-circles-in-html5-canvas
    const canvas = document.getElementById('canvasID');
    const ctx = canvas.getContext('2d');
    canvas.style.display = 'none';
    const circles = [];
    const radius = 20;

    function Circle(x, y, dx, dy, radius, color) {
        this.x = x;
        this.y = y;
        this.dx = dx;
        this.dy = dy;

        this.radius = radius;

        this.draw = function () {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
            ctx.strokeStyle = color;
            ctx.stroke();
        };

        this.update = function () {
            if (this.x + this.radius > 400 || this.x - this.radius < 0) {
                this.dx = -this.dx;
            }

            if (this.y + this.radius > 400 || this.y - this.radius < 0) {
                this.dy = -this.dy;
            }

            this.x += this.dx;
            this.y += this.dy;

            this.draw();
        };
    }

    for (let i = 0; i < 5; i++) {
        const color = `#${(0x1000000 + Math.random() * 0xffffff).toString(16).substr(1, 6)}`;
        const x = Math.random() * (400 - radius * 2) + radius;
        const y = Math.random() * (400 - radius * 2) + radius;

        const dx = (Math.random() - 0.5) * 2;
        const dy = (Math.random() - 0.5) * 2;

        circles.push(new Circle(x, y, dx, dy, radius, color));
    }

    function animate() {
        requestAnimationFrame(animate);
        ctx.clearRect(0, 0, 400, 400);

        for (let r = 0; r < 5; r++) {
            circles[r].update();
        }
    }

    animate();

    const map = new maplibregl.Map({
        container: 'map',
        zoom: 5,
        minZoom: 4,
        center: [95.899147, 18.088694],
        style: 'https://demotiles.maplibre.org/style.json'
    });

    map.on('load', () => {
        map.addSource('canvas-source', {
            type: 'canvas',
            canvas: 'canvasID',
            coordinates: [
                [91.4461, 21.5006],
                [100.3541, 21.5006],
                [100.3541, 13.9706],
                [91.4461, 13.9706]
            ],
            // 如果画布源是动画的则设置为true。如果画布是静态的,应将animate设置为false以提高性能。
            animate: true
        });

        map.addLayer({
            id: 'canvas-layer',
            type: 'raster',
            source: 'canvas-source'
        });
    });
</script>
</body>
</html>

🔍 代码解析

1. 创建Canvas动画

创建隐藏的Canvas元素,实现5个彩色圆形的动画效果:

  • Circle类定义圆形的位置、速度、半径和颜色
  • animate函数使用requestAnimationFrame实现平滑动画
  • 圆形到达边界时反弹

2. 初始化地图

使用 new maplibregl.Map() 创建地图实例,配置基本参数。本示例中心点设置在缅甸附近。

3. 添加Canvas数据源

map.load 事件中添加 canvas 类型数据源:

  • type: 'canvas': 指定为Canvas源
  • canvas: Canvas元素ID
  • coordinates: 地理坐标数组,定义Canvas在地图上的位置
  • animate: true: 启用动画同步

4. 添加栅格图层

创建 raster 类型图层引用Canvas数据源。

⚙️ 参数说明

参数 类型 必填 说明
container string 地图容器ID
style string 地图样式URL
center number, number 初始中心点,默认0, 0
zoom number 初始缩放级别,默认0

Canvas源配置

属性 类型 说明
type string 必须为 'canvas'
canvas string/HTMLCanvasElement Canvas元素ID或对象
coordinates array 四角地理坐标数组 左下, 右下, 右上, 左上
animate boolean 是否同步动画(默认false)

🎨 效果说明

运行代码后:

  • 地图显示缅甸区域(中心点 95.90°E, 18.09°N)
  • Canvas动画(5个彩色圆形)叠加在指定地理区域
  • 圆形在Canvas边界内反弹移动
  • 用户可正常交互(拖拽、缩放、旋转)

💡 常 见 问 题

Q1: Canvas坐标和地理坐标如何对应?

A: coordinates 数组定义Canvas四角对应的地理坐标,按顺序:左下、右下、右上、左上。

Q2: animate属性有什么作用?

A: 设置为true时,地图会自动监听Canvas的变化并更新显示。

Q3: 如何更新Canvas内容?

A: 直接操作Canvas上下文即可,地图会自动同步(需设置animate: true)。

📝 练习任务

  1. 基础练习:修改圆形数量和颜色
  2. 进阶挑战:添加交互功能,点击地图添加新圆形
  3. 拓展思考:如何实现Canvas内容的动态更新?

🌟 最佳实践

  1. 性能优化: 静态Canvas设置animate: false,动态Canvas设置animate: true
  2. 坐标配置: 确保coordinates顺序正确(左下、右下、右上、左上)
  3. 隐藏Canvas: 使用CSS隐藏原始Canvas元素
  4. 动画优化: 使用requestAnimationFrame确保流畅动画

🔗 延伸阅读


本文是MapLibre GL JS实践课程系列的一部分,欢迎关注收藏

相关推荐
界面开发小八哥17 小时前
界面控件DevExpress Blazor v26.1新版亮点 - Navigation(导航)
javascript·.net·界面控件·blazor·devexpress·ui开发
SendTomo18 小时前
send.wang(私传网)基于网页P2P直连传输大文件的优势
javascript·网络·webrtc·html5·p2p
学习星球19 小时前
Astro 全栈实战:拆解 RealWorld 项目
前端·javascript·架构·系统架构·前端框架·c5全栈
张元清20 小时前
React useTimeout Hook:声明式 setTimeout 与自动清理 (2026)
javascript·react.js
禁止摆烂_才浅20 小时前
JavaScript 类型判断:instanceof 与 constructor 原理深度解析
前端·javascript·面试
Asize21 小时前
HTTP 明明无状态,登录态怎么就保住了——React + Zustand + JWT 鉴权全流程拆解
前端·javascript
张人玉21 小时前
基于 Vue 3 + ECharts + Three.js + Express + SQLite——智慧城市数字孪生可视化平台
javascript·vue.js·信息可视化·sqlite·echarts
爱酱丶1 天前
VS Code 快速生成Vue3 + TypeScript + Setup 基础空模板
前端·javascript·typescript
Maxkim1 天前
在 GitHub 仓库里配一个 AI Code Reviewer,自动审查 PR
前端·javascript
NeverSettle_1 天前
Agent 如何快速调用公司接口?——CLI + Skill 实践与踩坑
前端·javascript·后端