首页 > 解决方案 > 如何获得路径笔划的“轮廓”,并获得点以创建填充的路径形状?

问题描述

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

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

结果如下:

在此处输入图像描述

标签: javascriptcanvaspathhtml5-canvasshapes

解决方案


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

但是,您可以使用复合操作来创建内部透明度。

例子

使用创建大纲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%);
    
}
<canvas id="canvas"></canvas>


推荐阅读