【问题标题】:How to position Path2D SVG element in canvas?如何在画布中定位 Path2D SVG 元素?
【发布时间】:2020-01-07 15:32:11
【问题描述】:

我正在画布上绘制一个 path2D SVG 形状。 问题是 moveTo 函数在使用 SVG 数据时似乎不起作用。

此代码笔说明了该问题。 https://codepen.io/grasmachien/pen/rNaJeBN

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

let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
p.moveTo(100,100)
ctx.fill(p);

有没有办法在不移动画布的情况下移动路径?

【问题讨论】:

    标签: javascript html5-canvas path-2d


    【解决方案1】:

    使用变换移动路径

    使用CanvasRenderingContext2D.translate

    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    
    let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
    ctx.translate(100, 100);
    ctx.fill(p);
    

    或使用CanvasRenderingContext2D.setTransform

    let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
    ctx.setTransform(1, 0, 0, 1, 100, 100);  // Also resets the transform before applying
    ctx.fill(p);
    

    或使用CanvasRenderingContext2D.transform

    let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
    ctx.transform(1, 0, 0, 1, 100, 100);  
    ctx.fill(p);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 2020-04-29
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多