
仅用canvas如何做地图呢目前市面上流行的无非leaflet、openlayers、cesium等但是归根到底都是基于canvas。本文仅做一个示例仅利用canvas创建地图流程如下1、依然是创建一个地图容器canvas需要定义宽和高单位像素。canvas idmapCanvas width907 height878/canvas2、生成canvas地图pageInit() { this.isMoving false; this.scale 1; this.originX 0; this.originY 0; this.startX 0; this.startY 0; const canvas document.getElementById(mapCanvas); const ctx canvas.getContext(2d); const img new Image(); img.src require(./img/map.png); img.onload () { this.drawImage(ctx, img); }; }, drawImage(ctx, img) { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.save(); ctx.translate(this.originX, this.originY); ctx.scale(this.scale, this.scale); ctx.drawImage(img, 0, 50, img.width, img.height); this.drawMarkers(ctx); ctx.restore(); }, drawMarkers(ctx) { this.sourceList.forEach(item { const markerImg new Image(); markerImg.src item.img; if (this.isMoving true) { ctx.drawImage(markerImg, item.position[0], item.position[1], markerImg.width, markerImg.height); // 调整标记大小 } else { markerImg.onload () { ctx.drawImage(markerImg, item.position[0], item.position[1], markerImg.width, markerImg.height); // 调整标记大小 }; } }); },3、由于是原始的canvas在创建地图的时候需要自己定义地图的放大、缩小、拖、拉、拽、单击、双击、hover等鼠标事件。addCanvasEventListeners() { const canvas document.getElementById(mapCanvas); canvas.addEventListener(wheel, this.handleWheel); canvas.addEventListener(mousedown, this.handleMouseDown); canvas.addEventListener(mousemove, this.handleMouseMove); canvas.addEventListener(mouseup, this.handleMouseUp); canvas.addEventListener(mouseout, this.handleMouseUp); canvas.addEventListener(click, this.handleClick); }, //鼠标滚轮放大缩小 handleWheel(event) { this.detailShow false; this.isMoving true; event.preventDefault(); const canvas document.getElementById(mapCanvas); const ctx canvas.getContext(2d); const img new Image(); img.src require(./img/map.png); img.onload () { const delta event.deltaY 0 ? -0.1 : 0.1; this.scale delta; this.scale Math.min(Math.max(0.5, this.scale), 3); // 限制缩放范围 this.drawImage(ctx, img); }; }, //鼠标按下 handleMouseDown(event) { this.isDragging true; this.startX event.clientX - this.originX; this.startY event.clientY - this.originY; }, //鼠标移动 handleMouseMove(event) { this.detailShow false; this.isMoving true; if (this.isDragging) { const canvas document.getElementById(mapCanvas); const ctx canvas.getContext(2d); const img new Image(); img.src require(./img/map.png); img.onload () { this.originX event.clientX - this.startX; this.originY event.clientY - this.startY; this.drawImage(ctx, img); } } }, //鼠标移动结束抬起左键 handleMouseUp() { this.isDragging false; }, //鼠标点击 handleClick(event) { },效果如下