js 实现垂直标尺
实现垂直标尺的 JavaScript 方法
使用 HTML 和 CSS 创建一个容器元素,设置其高度和样式以形成标尺的外观。通过 JavaScript 动态生成刻度线。

<div id="verticalRuler" style="position: relative; height: 500px; width: 30px; border-left: 1px solid black;"></div>
const ruler = document.getElementById('verticalRuler');
const height = ruler.offsetHeight;
const tickInterval = 10; // 像素间隔
for (let i = 0; i <= height; i += tickInterval) {
const tick = document.createElement('div');
tick.style.position = 'absolute';
tick.style.left = '0';
tick.style.top = `${i}px`;
tick.style.width = i % 50 === 0 ? '15px' : '10px'; // 长刻度
tick.style.height = '1px';
tick.style.backgroundColor = 'black';
ruler.appendChild(tick);
if (i % 50 === 0) {
const label = document.createElement('div');
label.textContent = i;
label.style.position = 'absolute';
label.style.left = '20px';
label.style.top = `${i}px`;
label.style.fontSize = '10px';
ruler.appendChild(label);
}
}
使用 Canvas 绘制垂直标尺
利用 Canvas API 可以更灵活地绘制标尺,适合需要动态更新或复杂样式的场景。

<canvas id="canvasRuler" width="50" height="500"></canvas>
const canvas = document.getElementById('canvasRuler');
const ctx = canvas.getContext('2d');
const height = canvas.height;
const tickInterval = 10;
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
for (let i = 0; i <= height; i += tickInterval) {
const tickLength = i % 50 === 0 ? 15 : 10;
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(tickLength, i);
ctx.stroke();
if (i % 50 === 0) {
ctx.font = '10px Arial';
ctx.fillText(i.toString(), tickLength + 5, i + 3);
}
}
响应式垂直标尺的实现
通过监听窗口大小变化事件,动态调整标尺的高度和刻度。
function createRuler() {
const ruler = document.getElementById('verticalRuler');
ruler.innerHTML = '';
const height = window.innerHeight;
ruler.style.height = `${height}px`;
for (let i = 0; i <= height; i += 10) {
const tick = document.createElement('div');
tick.style.top = `${i}px`;
ruler.appendChild(tick);
}
}
window.addEventListener('resize', createRuler);
createRuler();
使用 SVG 实现垂直标尺
SVG 提供矢量图形支持,适合需要缩放或高精度显示的标尺。
<svg id="svgRuler" width="50" height="500" xmlns="http://www.w3.org/2000/svg">
</svg>
const svg = document.getElementById('svgRuler');
const height = 500;
for (let i = 0; i <= height; i += 10) {
const tick = document.createElementNS('http://www.w3.org/2000/svg', 'line');
tick.setAttribute('x1', '0');
tick.setAttribute('y1', i);
tick.setAttribute('x2', i % 50 === 0 ? '15' : '10');
tick.setAttribute('y2', i);
tick.setAttribute('stroke', 'black');
svg.appendChild(tick);
if (i % 50 === 0) {
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '20');
text.setAttribute('y', i + 3);
text.setAttribute('font-size', '10');
text.textContent = i;
svg.appendChild(text);
}
}
以上方法可以根据具体需求选择,HTML/CSS 适合简单静态标尺,Canvas 和 SVG 适合动态或复杂样式场景。






