当前位置:首页 > 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实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…