vue 实现尺子
使用 Vue 实现尺子功能
在 Vue 中实现尺子功能通常需要结合 HTML5 Canvas 或 SVG 进行绘制,同时处理用户交互逻辑。以下是两种常见的实现方式:
基于 Canvas 的尺子实现
-
创建 Canvas 组件 在 Vue 组件中声明一个 Canvas 元素,并设置宽度和高度以适应需求。
<template> <div class="ruler-container"> <canvas ref="rulerCanvas" :width="width" :height="height"></canvas> </div> </template> -
绘制尺子刻度 在
mounted生命周期中调用绘制方法,使用 Canvas API 绘制刻度线和数字。mounted() { this.drawRuler(); }, methods: { drawRuler() { const ctx = this.$refs.rulerCanvas.getContext('2d'); ctx.clearRect(0, 0, this.width, this.height); // 绘制刻度线 for (let i = 0; i <= this.maxValue; i += this.step) { const x = i * this.pixelRatio; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, this.height); ctx.stroke(); // 绘制数字 ctx.fillText(i.toString(), x + 2, this.height / 2); } } } -
响应式调整 监听窗口大小变化或父容器尺寸变化,动态调整 Canvas 尺寸并重绘。
data() { return { width: 800, height: 30, maxValue: 100, step: 10, pixelRatio: 8 // 每单位对应的像素值 }; }
基于 SVG 的尺子实现
-
创建 SVG 组件 使用 SVG 元素绘制尺子,利用 Vue 的动态渲染能力生成刻度。
<template> <svg class="ruler" :width="width" :height="height"> <!-- 背景 --> <rect width="100%" height="100%" fill="#f5f5f5" /> <!-- 刻度线 --> <line v-for="i in ticks" :key="i" :x1="i * pixelRatio" :y1="0" :x2="i * pixelRatio" :y2="height" stroke="#333" /> <!-- 刻度数字 --> <text v-for="i in numberedTicks" :key="'text-' + i" :x="i * pixelRatio + 2" :y="height / 2" fill="#333" > {{ i }} </text> </svg> </template> -
计算刻度数据 在计算属性中生成刻度位置和需要显示数字的刻度。
computed: { ticks() { return Array.from({ length: this.maxValue / this.step + 1 }, (_, i) => i * this.step); }, numberedTicks() { return this.ticks.filter(i => i % (this.step * 5) === 0); } } -
交互处理 添加鼠标移动事件监听,显示当前鼠标位置的刻度值。
methods: { handleMouseMove(event) { const rect = this.$el.getBoundingClientRect(); const x = event.clientX - rect.left; this.currentValue = Math.round(x / this.pixelRatio); } }
样式优化
为尺子添加 CSS 样式,使其更符合实际尺子的外观。
.ruler-container {
overflow-x: auto;
border: 1px solid #ddd;
}
.ruler {
font-size: 10px;
user-select: none;
}
动态单位切换
通过计算属性支持不同单位(如像素、厘米、英寸)的切换。

computed: {
pixelRatio() {
switch (this.unit) {
case 'cm': return 37.8; // 1cm ≈ 37.8px
case 'inch': return 96; // 1inch = 96px
default: return 1; // 像素
}
}
}
以上两种方法均可实现尺子功能,Canvas 更适合复杂绘制场景,而 SVG 更易于维护和动态更新。根据实际需求选择合适的技术方案。






