当前位置: 首页 > news >正文

MapLibre GL JS第29课:添加Canvas源

📌 学习目标

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

🎯 核心概念

向地图添加Canvas数据源。

💻 完 整 代 码

代码示例

//Animation from https://javascript.tutorials24x7.com/blog/how-to-draw-animated-circles-in-html5-canvasconstcanvas=document.getElementById('canvasID');constctx=canvas.getContext('2d');canvas.style.display='none';constcircles=[];constradius=20;functionCircle(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(leti=0;i<5;i++){constcolor=`#${(0x1000000+Math.random()*0xffffff).toString(16).substr(1,6)}`;constx=Math.random()*(400-radius*2)+radius;consty=Math.random()*(400-radius*2)+radius;constdx=(Math.random()-0.5)*2;constdy=(Math.random()-0.5)*2;circles.push(newCircle(x,y,dx,dy,radius,color));}functionanimate(){requestAnimationFrame(animate);ctx.clearRect(0,0,400,400);for(letr=0;r<5;r++){circles[r].update();}}animate();constmap=newmaplibregl.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'});});

代码示例

<!DOCTYPEhtml><htmllang="en"><head><title>Add a canvas source</title><metaproperty="og:description"content="向地图添加画布源。"/><metaproperty="og:created"content="2025-06-25"/><metacharset='utf-8'><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel='stylesheet'href='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.css'/><scriptsrc='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><canvasid="canvasID"width="400"height="400">Canvas not supported</canvas><divid="map"></div><script>//Animation from https://javascript.tutorials24x7.com/blog/how-to-draw-animated-circles-in-html5-canvasconstcanvas=document.getElementById('canvasID');constctx=canvas.getContext('2d');canvas.style.display='none';constcircles=[];constradius=20;functionCircle(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(leti=0;i<5;i++){constcolor=`#${(0x1000000+Math.random()*0xffffff).toString(16).substr(1,6)}`;constx=Math.random()*(400-radius*2)+radius;consty=Math.random()*(400-radius*2)+radius;constdx=(Math.random()-0.5)*2;constdy=(Math.random()-0.5)*2;circles.push(newCircle(x,y,dx,dy,radius,color));}functionanimate(){requestAnimationFrame(animate);ctx.clearRect(0,0,400,400);for(letr=0;r<5;r++){circles[r].update();}}animate();constmap=newmaplibregl.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数据源。

⚙️ 参数说明

参数类型必填说明
containerstring地图容器ID
stylestring地图样式URL
center[number, number]初始中心点,默认[0, 0]
zoomnumber初始缩放级别,默认0

Canvas源配置

属性类型说明
typestring必须为 ‘canvas’
canvasstring/HTMLCanvasElementCanvas元素ID或对象
coordinatesarray四角地理坐标数组 [左下, 右下, 右上, 左上]
animateboolean是否同步动画(默认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确保流畅动画

🔗 延伸阅读

  • Map API文档

  • MapLibre GL JS 官方文档

  • [下一课预告]:将继续学习地图图层的基础知识


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

http://www.rkmt.cn/news/1430970.html

相关文章:

  • 2026年AI论文网站深度评测:6款工具全能表现得分排名
  • Win7离线环境救星:手把手教你修改4个XML和1个注册表,彻底解决VMware Converter 6.2无法启动服务报错
  • 实验一 常用网络命令的使用
  • Arduino雨水监测系统:从传感器原理到物联网报警实现
  • TrafficMonitor插件完全指南:如何将Windows任务栏打造成全能信息中心
  • 因民事养老金管理失误,英国政府拒绝向Capita授予5.63亿英镑合同
  • [开源] 多部门会签文档进度自动重建系统:面向医院行政与临床协同的OCR+状态机追踪工具
  • AnyFlip下载器:三步实现电子书PDF转换的跨平台解决方案
  • 老Mac焕新记:手把手教你用U盘和Ghost镜像给iMac安装纯净版Win7
  • 2026年5月更新:河北有实力的平台钢格板定制厂家选哪家?专业解析与推荐 - 2026年企业资讯
  • 第 20 篇 搭建 Kubernetes 实验环境:Minikube 与 kubectl
  • 2026年国内GEO服务商实力盘点:从短期流量到长效资产的转型之路 - GEO优化
  • 2026降AI率工具红黑榜:降AI率工具怎么选?一文讲透
  • 郑州茅台酒回收商家排行:郑州闲置酒水回收、郑州高价名酒回收、郑州高端名酒回收、郑州上门收茅台、郑州专业老酒回收选择指南 - 优质品牌商家
  • 2026年5月更新:聚焦安徽市场,甄选高性价比安全生产培训直销服务商 - 2026年企业资讯
  • 如何高效管理浏览器下载:Motrix WebExtension专业解决方案
  • Windows高DPI缩放总让你头疼?从‘模糊’到‘清晰’的完整设置指南(含Win10/11避坑清单)
  • C# 重写
  • 干货合集:2026年实测靠谱的专业降AI率平台
  • Perseus原生库:无偏移地址设计的游戏脚本补丁架构解析
  • Parallels Desktop 17保姆级教程:给CentOS 7虚拟机配个固定IP,开发调试再也不怕IP变来变去
  • Arduino电位器控制RGB LED:从模拟输入到PWM输出的完整实践
  • 2624张光伏缺陷图像:ELPV数据集如何重塑AI质检标准
  • 西安好阿姨家政,专业育婴师推荐的不二之选 - myqiye
  • Veo多场景视频生成合规红线清单,2024最新GDPR+《生成式AI服务管理暂行办法》双标适配指南
  • 福建外墙涂料多少钱?丽哆美价格合理 - mypinpai
  • 求推荐内蒙古生产小型水泥构件的源头厂家 - 工业品牌热点
  • 生成式AI视频侵权判定标准首次公开:国家版权中心2024新规解读与企业自查清单
  • 知识图谱与 Agent Harness 的深度融合
  • 英雄联盟玩家必备:本地化智能助手如何彻底改变你的游戏体验