js 实现垂直标尺
实现垂直标尺的 JavaScript 方法
使用 Canvas 绘制垂直标尺
通过 HTML5 Canvas 可以动态绘制标尺刻度,适合需要自定义样式的场景。

const canvas = document.getElementById('rulerCanvas');
const ctx = canvas.getContext('2d');
const height = 500; // 标尺高度
const unit = 10; // 刻度单位(像素)
canvas.width = 40; // 标尺宽度
canvas.height = height;
ctx.fillStyle = '#f0f0f0';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制刻度线
for (let y = 0; y <= height; y += unit) {
const lineWidth = y % 50 === 0 ? 15 : (y % 10 === 0 ? 10 : 5);
ctx.beginPath();
ctx.moveTo(canvas.width - lineWidth, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
// 添加数字标签(每50像素)
if (y % 50 === 0) {
ctx.font = '10px Arial';
ctx.fillText(y.toString(), 5, y + 3);
}
}
使用 CSS 和 DOM 元素模拟标尺
通过动态生成 div 元素实现,适合需要响应式布局的场景。

<div id="verticalRuler" style="position: relative; height: 500px; width: 30px; background: #f0f0f0;"></div>
<script>
const ruler = document.getElementById('verticalRuler');
const height = 500;
const unit = 10;
for (let y = 0; y <= height; y += unit) {
const tick = document.createElement('div');
tick.style.position = 'absolute';
tick.style.right = '0';
tick.style.top = `${y}px`;
tick.style.height = '1px';
tick.style.backgroundColor = '#000';
// 长刻度(每50像素)
if (y % 50 === 0) {
tick.style.width = '15px';
const label = document.createElement('div');
label.textContent = y;
label.style.position = 'absolute';
label.style.right = '20px';
label.style.top = `${y - 6}px`;
ruler.appendChild(label);
} else if (y % 10 === 0) {
tick.style.width = '10px';
} else {
tick.style.width = '5px';
}
ruler.appendChild(tick);
}
</script>
使用 SVG 实现矢量标尺
适合需要缩放且保持清晰度的场景。
<svg id="svgRuler" width="40" height="500" style="background: #f0f0f0;"></svg>
<script>
const svg = document.getElementById('svgRuler');
const height = 500;
const unit = 10;
for (let y = 0; y <= height; y += unit) {
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', y % 50 === 0 ? 5 : (y % 10 === 0 ? 10 : 15));
line.setAttribute('x2', '40');
line.setAttribute('y1', y);
line.setAttribute('y2', y);
line.setAttribute('stroke', '#000');
// 添加文本标签
if (y % 50 === 0) {
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '0');
text.setAttribute('y', y + 3);
text.textContent = y;
text.setAttribute('font-size', '10px');
svg.appendChild(text);
}
svg.appendChild(line);
}
</script>
关键注意事项
- 动态调整:监听窗口大小变化事件(
resize),重新计算标尺刻度位置。 - 性能优化:对于高频更新的场景,推荐使用 Canvas 或 SVG 而非 DOM 操作。
- 交互功能:可通过事件监听实现标尺拖拽或点击定位功能。






