You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将KonvaJS的Stage尺寸单位设为毫米(mm)而非像素(px)?

如何无需手动修改画布尺寸,将KonvaJS的Stage尺寸单位从像素(px)改为毫米(mm)?

KonvaJS的Stage组件本身不直接支持毫米作为尺寸单位,其width和height参数仅接受数值类型,默认单位为像素。要实现用毫米定义Stage尺寸且无需手动调整画布,核心思路是将毫米值转换为对应的像素值,再传递给Stage的参数。

实现步骤

  1. 毫米转像素的核心逻辑
    根据物理单位换算关系:1英寸 = 25.4毫米,而屏幕的DPI(每英寸像素数)决定了1英寸对应的像素数量。因此,毫米转像素的公式为:
    像素值 = 毫米值 × (DPI / 25.4)

  2. 编写转换函数
    你可以使用默认屏幕DPI(通常为96),或者获取设备实际DPI来提升精度:

    方式一:使用默认DPI(快速实现)

    // 毫米转像素函数,默认DPI为96
    function mmToPx(mm) {
      const defaultDPI = 96;
      return mm * (defaultDPI / 25.4);
    }
    

    方式二:获取设备实际DPI(更高精度)

    通过创建一个隐藏的1英寸元素,获取其实际像素宽度来得到设备DPI:

    // 获取设备实际DPI
    function getActualDPI() {
      const inchElement = document.createElement('div');
      inchElement.style.width = '1in';
      inchElement.style.height = '1in';
      inchElement.style.position = 'absolute';
      inchElement.style.visibility = 'hidden';
      document.body.appendChild(inchElement);
      const dpi = inchElement.offsetWidth;
      document.body.removeChild(inchElement);
      return dpi;
    }
    
    // 基于实际DPI的毫米转像素函数
    function mmToPx(mm) {
      const dpi = getActualDPI();
      return mm * (dpi / 25.4);
    }
    
  3. 用毫米值创建Stage
    直接调用转换函数,将毫米值转为像素后传入Stage参数:

    var stage = new Konva.Stage({
      width: mmToPx(100),  // 对应100毫米宽度
      height: mmToPx(150), // 对应150毫米高度
      container: 'containerId'
    });
    

说明

这种方式无需手动修改画布尺寸,Konva会根据转换后的像素值自动创建对应大小的画布。本质上是通过单位换算绕开Konva仅支持像素参数的限制,实现用毫米定义Stage尺寸的效果。

内容的提问来源于stack exchange,提问作者Billy Adelphia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:56:06