【问题标题】:How can I get the "outline" of a Path stroke, and get the points to create a filled Path shape?如何获得路径笔划的“轮廓”,并获得点以创建填充的路径形状?
【发布时间】:2021-01-28 01:40:25
【问题描述】:

我想检索'outlinestroke'的对应点并将其保存为Shape,而不是“带有笔触的路径”

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineWidth = 12;
ctx.lineCap = 'round'
ctx.quadraticCurveTo(20, 100, 200, 20);
ctx.stroke();
</script> 

</body>
</html>

这是代码的结果:

但是我想要这个笔画的轮廓,然后把它变成一个路径并给它一个笔画。 填充应该是透明的。 而且只有一个小轮廓。

有没有办法将笔划“追踪或转换”为轮廓路径以获得以下结果:

如果这是不可能的: 在绘制之前,使用给定的点来定义路径的形状。

这是我尝试过的:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var width = 12;
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineWidth = width;
ctx.quadraticCurveTo(20, 100, 200, 20);
ctx.stroke();

ctx.beginPath();
ctx.lineWidth = 1;
ctx.fillStyle = "#ccc";

ctx.moveTo(20-width/2, 270);
ctx.quadraticCurveTo(20-width/2, 350+width/2, 200-width/2, 270+width/2);
ctx.lineTo(200-width/2, 270-width/2);
ctx.quadraticCurveTo(20+width/2, 350-width/2, 20+width/2, 270-width/2);
ctx.lineTo(20-width/2, 270);
ctx.fillStyle = "#999";

ctx.fill();
ctx.stroke();
ctx.closePath();

结果如下:

【问题讨论】:

    标签: javascript canvas path html5-canvas shapes


    【解决方案1】:

    没有 API 功能可以将笔划轮廓转换为路径。

    但是,您可以使用 composite operation 来创建内部透明度。

    示例

    使用globalCompositeOperation = "destination-out";创建轮廓

    渐变只是为了显示它是透明的。

    const OUTLINE_WIDTH = 1; // in pixels
    
    var ctx = canvas.getContext("2d");
    ctx.lineWidth = 22;
    ctx.lineCap = 'round'
    ctx.beginPath();
    ctx.moveTo(20, 20);
    ctx.quadraticCurveTo(20, 100, 200, 20);
    ctx.stroke();
    ctx.globalCompositeOperation = "destination-out";
    ctx.lineWidth = 22 - OUTLINE_WIDTH * 2;
    ctx.stroke();
    
    ctx.globalCompositeOperation = "source-over"; // restore default
    canvas {
        border:1px solid #aaa;
        background: linear-gradient(90deg, rgba(180,255,224,1) 0%, rgba(169,169,255,1) 100%);
        
    }
    &lt;canvas id="canvas"&gt;&lt;/canvas&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      相关资源
      最近更新 更多