js实现标尺
实现标尺的 JavaScript 方法
使用 Canvas 绘制标尺
通过 HTML5 的 Canvas API 可以灵活绘制标尺,支持自定义刻度、颜色和方向。
const canvas = document.getElementById('rulerCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const scale = 1; // 缩放比例
const unit = 'px'; // 单位
// 水平标尺
function drawHorizontalRuler() {
ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
// 绘制主刻度
for (let i = 0; i < width; i += 50 * scale) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, 15);
ctx.stroke();
ctx.fillText(i + unit, i + 2, 12);
}
// 绘制次刻度
for (let i = 0; i < width; i += 10 * scale) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, 8);
ctx.stroke();
}
}
使用 CSS 和 DOM 创建标尺
通过动态生成 DOM 元素和 CSS 样式实现轻量级标尺。
function createCSSRuler(containerId, orientation = 'horizontal') {
const container = document.getElementById(containerId);
const ruler = document.createElement('div');
ruler.className = 'ruler ' + orientation;
// 生成刻度
for (let i = 0; i < 1000; i += 10) {
const tick = document.createElement('div');
tick.className = 'tick';
if (i % 50 === 0) {
tick.classList.add('major-tick');
tick.textContent = i;
}
ruler.appendChild(tick);
}
container.appendChild(ruler);
}
对应 CSS 样式:
.ruler {
position: relative;
background: #f0f0f0;
overflow: hidden;
}
.ruler.horizontal {
height: 20px;
width: 100%;
}
.tick {
position: absolute;
background: #999;
}
.horizontal .tick {
width: 1px;
height: 5px;
bottom: 0;
}
.horizontal .major-tick {
height: 10px;
}
使用 SVG 实现矢量标尺
SVG 方案适合需要缩放而不失真的场景。
function createSVGRuler(containerId, length = 500) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', length);
svg.setAttribute('height', 20);
for (let i = 0; i < length; i += 10) {
const tick = document.createElementNS("http://www.w3.org/2000/svg", "line");
tick.setAttribute('x1', i);
tick.setAttribute('y1', 20);
tick.setAttribute('x2', i);
tick.setAttribute('y2', i % 50 === 0 ? 10 : 15);
tick.setAttribute('stroke', '#000');
svg.appendChild(tick);
if (i % 50 === 0) {
const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.setAttribute('x', i + 2);
text.setAttribute('y', 8);
text.textContent = i;
svg.appendChild(text);
}
}
document.getElementById(containerId).appendChild(svg);
}
响应式标尺实现
添加窗口大小变化的监听,动态调整标尺尺寸。
window.addEventListener('resize', () => {
const ruler = document.querySelector('.ruler');
if (ruler) {
ruler.style.width = window.innerWidth + 'px';
// 重新绘制刻度逻辑
}
});
专业库推荐
对于复杂需求,可以考虑以下库:
- ruler.js:提供多种标尺样式和单位转换
- fabric.js:在 Canvas 基础上提供更丰富的图形功能
- D3.js:适合数据可视化场景的标尺实现
每种实现方式各有优劣:Canvas 适合高性能绘制,CSS 方案更轻量,SVG 则便于缩放。选择时应根据具体需求考虑性能、兼容性和功能复杂度。







