当前位置: 首页 > 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.jsqmd.com/news/919648/

相关文章:

  • NPN晶体管多谐振荡器:从RC定时到LED交替闪烁的电路设计与实践
  • 陕西 RAG 权重调整技术对于 GEO 优化的深度调查:企来客逆 RAG 技术升级真相揭示
  • 纳米 AI 搜索新手极速上手指南
  • 2026年AI论文网站深度评测:6款工具全能表现得分排名
  • Arm编译器更新订阅与功能安全认证维护指南
  • Win7离线环境救星:手把手教你修改4个XML和1个注册表,彻底解决VMware Converter 6.2无法启动服务报错
  • 从零打造可调光LED台灯:电路设计、仿真与焊接实战指南
  • MapLibre GL JS第30课:添加视频
  • 2026年西安靠谱的育婴师推荐排名 - mypinpai
  • Claude Code 迎来重磅更新!v2.1.156 v2.1.157 双版本发布:本地插件免市集加载、多 Worktree 自由切换与大波 Bug 修复
  • 一个人写了一套店群矩阵自动化软件:我是如何干掉繁琐切号流程与并发内存泄漏的
  • [开源] 医保基金流向追踪图:面向医保办自查与汇报的可视化分析系统
  • 2026年养老保姆推荐平台排名,价格透明吗? - mypinpai
  • MobileNet-Yolo深度解析:超轻量级实时目标检测的终极实战指南
  • 朱光亚与一个民族最深沉的精神底色(潜龙在渊)
  • 终极指南:如何免费获取和使用Poppins多语言字体
  • 如何快速掌握MoviePilot批量重命名:完整操作指南与实战技巧
  • 038、替换激活函数能涨几个点?SiLU、Mish、GELU、ReLU 在 YOLO 上的消融实验
  • 大模型核心基础知识(12)—机器学习的基本概念与常见方法
  • MapLibre GL JS第31课:添加实时数据
  • 告别手动对账:3步实现美团饿了么百度外卖订单自动化采集 [特殊字符]
  • OBS-Multi-RTMP:一键同步多平台直播,让内容传播效率提升300%
  • 2026年适配维普AI智能降重工具横评:亲测8款工具,把AIGC率稳控在安全线内
  • 039、卷积模块替换实验:GhostConv、DSConv、DynamicConv 的精度-速度权衡
  • 实验一 常用网络命令的使用
  • TrafficMonitor插件完全指南:如何将Windows任务栏打造成全能信息中心
  • Arduino雨水监测系统:从传感器原理到物联网报警实现
  • 2026年徐州讯灵AI品牌推荐 - mypinpai
  • Display Driver Uninstaller:彻底解决显卡驱动残留问题的系统管理员必备工具
  • 【新手保姆级教程】OpenClaw v2.7.8 一键安装教程,Windows 环境快速部署(包含安装包)