js实现图层标注
使用Canvas实现图层标注
Canvas是HTML5提供的绘图API,适合实现动态图层标注。通过Canvas的2D上下文可以绘制文字、图形和路径。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 绘制文字标注
ctx.font = '16px Arial';
ctx.fillStyle = 'red';
ctx.fillText('标注文字', 100, 100);
// 绘制矩形标注框
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.strokeRect(90, 90, 120, 30);
使用SVG实现矢量标注
SVG是矢量图形格式,标注内容缩放不失真。通过DOM操作可以动态添加标注元素。

const svg = document.getElementById('svg-container');
// 创建文字标注
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '100');
text.setAttribute('y', '100');
text.setAttribute('fill', 'red');
text.textContent = 'SVG标注';
// 创建背景矩形
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '90');
rect.setAttribute('y', '90');
rect.setAttribute('width', '120');
rect.setAttribute('height', '30');
rect.setAttribute('stroke', 'blue');
svg.appendChild(rect);
svg.appendChild(text);
基于HTML/CSS的DOM标注
对于简单标注需求,可以直接使用HTML元素配合CSS定位。
const marker = document.createElement('div');
marker.className = 'annotation-marker';
marker.textContent = 'DOM标注';
marker.style.left = '100px';
marker.style.top = '100px';
document.body.appendChild(marker);
对应CSS样式:

.annotation-marker {
position: absolute;
background: rgba(255,255,0,0.5);
padding: 5px;
border: 1px solid black;
}
使用第三方库实现高级标注
专业地图或图形库提供更完善的标注功能:
- Leaflet.js的地图标记
- OpenLayers的矢量标注
- Fabric.js的画布标注工具
// 使用Fabric.js示例
const canvas = new fabric.Canvas('canvas');
const text = new fabric.Text('Fabric标注', {
left: 100,
top: 100,
fill: 'green',
fontSize: 20
});
canvas.add(text);
实现交互式标注
为标注添加交互功能需要事件监听:
canvas.addEventListener('click', (e) => {
const x = e.clientX - canvas.offsetLeft;
const y = e.clientY - canvas.offsetTop;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(`点击位置: ${x}, ${y}`, x, y);
});






