微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获得路径笔触的“轮廓”,并获取点以创建填充的路径形状?

如何解决如何获得路径笔触的“轮廓”,并获取点以创建填充的路径形状?

我想检索“轮廓描边”的对应点并将其另存为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>

这是代码的结果:

Curve on canvas

但是我想获得此笔画的轮廓,然后将其变成“路径”并对其进行笔画。 填充应该是透明的。 而且只有一个小轮廓。

有没有一种方法可以将描边“跟踪或转换”为轮廓路径以获得以下结果:

enter image description here

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

这是我尝试过的:

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,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();

结果如下:

enter image description here

解决方法

没有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,1) 100%);
    
}
<canvas id="canvas"></canvas>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。