问题描述
我想检索“轮廓描边”的对应点并将其另存为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,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();
结果如下:
解决方法
没有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>