javascript - 如何获得路径笔划的“轮廓”,并获得点以创建填充的路径形状?
问题描述
我想检索'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();
结果如下:
解决方案
没有 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>
推荐阅读
- mysql - 如何在不重复计算的情况下执行 SQL
- c - MSBuild 无法从 CLI 构建。无效的静态调用语法
- wpf - keyDown 事件在按下并释放第二个键后停止触发
- python - 转换数据帧的 2 列,在对应的 uint16_t 的列中存储两个 uint8_t
- c++ - 如何定义构造函数c ++
- java - 使用 GLES30 进行 VAO 渲染:偏移量/长度错误!!!!!!错误
- c# - 使用 Span 存储单词集合的有效方法是什么
? - python - AttributeError:“str”对象没有属性“add_picture”
- amazon-web-services - AWS Cognito 客户端 SDK v3 在运行管理员禁用用户命令时返回未定义的“byteLength”
- c++ - 在方法调用参数中创建对象返回空对象?