【问题标题】:What is the unit of x and y in canvasrendering2d.moveTo() in canvas of html5?html5的画布渲染2d.move To()中x和y的单位是什么?
【发布时间】:2022-01-13 21:42:05
【问题描述】:

每个人。我制作了一个不同大小的画布,并为 moveTo() 和 lineTo() 绘制了一条具有相同值的线,但我得到了不同大小的线。

这是代码。

    function testCanvas(height, width){
    canvas = document.createElement("canvas");
    ctx = canvas.getContext('2d');

    canvas.style.display = "inline-block";
    canvas.style.border = "1px solid black";

    canvas.height = height;
    canvas.width = width;

    document.getElementById("chartContainer").appendChild(canvas);
    }

    function drawLine(x1, y1, x2, y2){
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    
    ctx.stroke();
    }
  1. 当我去检查元素 > 控制台并调用时:

     testCanvas(300,300);
     drawLine(10,50,110,50);
    

    testCanvas(150,150);
    drawLine(10,50,110,50);

行的长度不相等。 现在,如果 moveTo 和 lineTo 的输入以像素为单位,这些线的长度是否相同?这里的默认单位是什么?

【问题讨论】:

    标签: javascript html5-canvas html-rendering


    【解决方案1】:

    本身并没有真正的“单位”。
    这些值取决于当前转换矩阵 (CTM),您可以使用 scale()rotate()transform() 等方法进行修改。

    但使用默认 CTM,1 的值将代表画布输出缓冲区中的 1 个像素。

    所以这里肯定会发生的是您的画布通过 CSS 调整大小。
    CSS 将拉伸或收缩画布,使其图像看起来与其缓冲区实际不同:

    let canvas, ctx;
    function testCanvas(height, width) {
      canvas = document.createElement("canvas");
      ctx = canvas.getContext('2d');
    
      canvas.style.display = "inline-block";
      canvas.style.border = "1px solid black";
    
      canvas.height = height;
      canvas.width = width;
    
      document.getElementById("chartContainer").appendChild(canvas);
    }
    
    function drawLine(x1, y1, x2, y2) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
    
      ctx.stroke();
    }
    
    testCanvas(300,300);
    drawLine(10,50,110,50);
    
    testCanvas(150,150);
    drawLine(10,50,110,50);
    canvas { background: #CCC; vertical-align: top }
    :checked ~ div canvas {
      width: 300px;
      height: 300px;
    }
    <input type=checkbox>set size through CSS
    <div id="chartContainer"></div>

    为避免这种情况,请避免通过 CSS 设置画布大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多