当前位置:首页 > JavaScript

js实现刻度

2026-02-01 09:28:43JavaScript

刻度实现的基本方法

使用JavaScript实现刻度可以通过Canvas或SVG进行绘制。Canvas适合动态生成的图形,SVG适合需要交互的场景。

Canvas绘制刻度

创建Canvas元素并设置宽高:

<canvas id="scaleCanvas" width="400" height="100"></canvas>

JavaScript代码实现刻度绘制:

js实现刻度

const canvas = document.getElementById('scaleCanvas');
const ctx = canvas.getContext('2d');

function drawScale(start, end, interval, majorHeight, minorHeight) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();

  // 绘制主刻度
  for(let i = start; i <= end; i += interval) {
    const x = (i - start) * (canvas.width / (end - start));
    ctx.moveTo(x, canvas.height);
    ctx.lineTo(x, canvas.height - majorHeight);
    ctx.fillText(i.toString(), x - 5, canvas.height - majorHeight - 5);
  }

  // 绘制次刻度
  for(let i = start; i <= end; i += interval/2) {
    const x = (i - start) * (canvas.width / (end - start));
    ctx.moveTo(x, canvas.height);
    ctx.lineTo(x, canvas.height - minorHeight);
  }

  ctx.stroke();
}

drawScale(0, 100, 10, 20, 10);

SVG实现刻度

创建SVG元素:

<svg id="scaleSVG" width="400" height="100"></svg>

JavaScript代码实现:

js实现刻度

const svg = document.getElementById('scaleSVG');

function createScale(start, end, interval, majorHeight, minorHeight) {
  svg.innerHTML = '';
  const scaleLength = end - start;

  // 创建主刻度
  for(let i = start; i <= end; i += interval) {
    const x = (i - start) * (svg.width.baseVal.value / scaleLength);
    const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    line.setAttribute("x1", x);
    line.setAttribute("y1", svg.height.baseVal.value);
    line.setAttribute("x2", x);
    line.setAttribute("y2", svg.height.baseVal.value - majorHeight);
    line.setAttribute("stroke", "black");
    svg.appendChild(line);

    const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    text.setAttribute("x", x - 5);
    text.setAttribute("y", svg.height.baseVal.value - majorHeight - 5);
    text.textContent = i.toString();
    svg.appendChild(text);
  }

  // 创建次刻度
  for(let i = start; i <= end; i += interval/2) {
    const x = (i - start) * (svg.width.baseVal.value / scaleLength);
    const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    line.setAttribute("x1", x);
    line.setAttribute("y1", svg.height.baseVal.value);
    line.setAttribute("x2", x);
    line.setAttribute("y2", svg.height.baseVal.value - minorHeight);
    line.setAttribute("stroke", "black");
    svg.appendChild(line);
  }
}

createScale(0, 100, 10, 20, 10);

动态刻度实现

实现可交互的动态刻度尺:

const scaleContainer = document.getElementById('scaleContainer');
let isDragging = false;
let startX = 0;
let scrollLeft = 0;

scaleContainer.addEventListener('mousedown', (e) => {
  isDragging = true;
  startX = e.pageX - scaleContainer.offsetLeft;
  scrollLeft = scaleContainer.scrollLeft;
});

window.addEventListener('mouseup', () => {
  isDragging = false;
});

window.addEventListener('mousemove', (e) => {
  if(!isDragging) return;
  e.preventDefault();
  const x = e.pageX - scaleContainer.offsetLeft;
  const walk = (x - startX) * 2;
  scaleContainer.scrollLeft = scrollLeft - walk;
});

function generateDynamicScale() {
  const scaleWidth = 2000;
  scaleContainer.style.width = '400px';
  scaleContainer.style.overflowX = 'scroll';
  scaleContainer.innerHTML = `
    <div style="width:${scaleWidth}px; height:50px; position:relative; border-top:1px solid #000">
      ${Array.from({length: scaleWidth/10}, (_, i) => 
        i % 10 === 0 ? 
          `<div style="position:absolute; left:${i*10}px; top:0; height:20px; width:1px; background:#000"></div>
           <div style="position:absolute; left:${i*10-5}px; top:25px;">${i}</div>` :
          `<div style="position:absolute; left:${i*10}px; top:10px; height:10px; width:1px; background:#ccc"></div>`
      ).join('')}
    </div>
  `;
}

generateDynamicScale();

响应式刻度尺

实现适应不同屏幕尺寸的刻度尺:

function responsiveScale() {
  const container = document.getElementById('responsiveScale');
  const width = window.innerWidth * 0.8;
  container.style.width = `${width}px`;

  const majorInterval = width > 600 ? 50 : 100;
  const minorInterval = majorInterval / 5;

  container.innerHTML = `
    <svg width="100%" height="50">
      ${Array.from({length: Math.floor(width/majorInterval)}, (_, i) => 
        `<line x1="${i*majorInterval}" y1="50" x2="${i*majorInterval}" y2="30" stroke="#000" stroke-width="1"/>
         <text x="${i*majorInterval-10}" y="25">${i*majorInterval}</text>
         ${Array.from({length: 4}, (_, j) => 
           `<line x1="${i*majorInterval + (j+1)*minorInterval}" y1="50" 
                 x2="${i*majorInterval + (j+1)*minorInterval}" y2="40" stroke="#999" stroke-width="0.5"/>`
         ).join('')}`
      ).join('')}
    </svg>
  `;
}

window.addEventListener('resize', responsiveScale);
responsiveScale();

以上方法提供了从基础到高级的刻度实现方案,可以根据具体需求选择适合的方式。Canvas方案适合需要频繁更新的动态刻度,SVG方案适合需要交互的场景,而动态和响应式方案则提供了更完善的用户体验。

标签: 刻度js
分享给朋友:

相关文章

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…