使用三次贝塞尔曲线平滑SVG路径
创作时间:
作者:
@小白创作中心
使用三次贝塞尔曲线平滑SVG路径
引用
CSDN
1.
https://blog.csdn.net/qq_40646695/article/details/138533014
在SVG元素中绘制直线相对简单,但要实现平滑曲线则需要一些三角学知识。本文将详细介绍如何使用三次贝塞尔曲线来平滑SVG路径,并通过具体代码示例展示实现过程。
我们有一个表示线段点坐标的数组:
const points = [[5, 10], [10, 40], [40, 30], [60, 5], [90, 45], [120, 10], [150, 45], [200, 10]];
HTML页面中的SVG元素:
<svg viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" class="svg"></svg>
我们想从点数组中创建一个<path>元素。
创建path由这个点
<path>元素的d属性始终以移动到命令:M x,y开头,后面跟着几个命令,具体取决于形状的类型。结果类似于:
<path d="M 10,20 L 15,25 L 20,35">
表示直线。首先,让我们创建一个通用的svgPath函数,它有两个参数:point数组和command函数。
// Render the svg <path> element
// I: - points (array): points coordinates
// - command (function)
// I: - point (array) [x,y]: current point coordinates
// - i (integer): index of 'point' in the array 'a'
// - a (array): complete array of points coordinates
// O: - (string) a svg path command
// O: - (string): a Svg <path> element
const svgPath = (points, command) => {
// build the d attributes by looping over the points
const d = points.reduce((acc, point, i, a) => i === 0
// if first point
? `M ${point[0]},${point[1]}`
// else
: `${acc} ${command(point, i, a)}`
, '');
return `<path d="${d}" fill="none" stroke="grey" />`;
};
现在,让我们创建两个命令函数:
lineCommand:画直线。bezierCommand:画平滑的线。
画直线
直线需要指令line to,以字母L开头,后跟终点x、y的坐标。绘制直线的基本lineCommand函数:
// Svg path line command
// I: - point (array) [x, y]: coordinates
// O: - (string) 'L x,y': svg line command
const lineCommand = point => `L ${point[0]} ${point[1]}`;
现在我们可以用它从点数组中画一条线:
const svg = document.querySelector('.svg');
svg.innerHTML = svgPath(points, lineCommand);
这给出了以下结果:
画平滑的曲线
三次贝塞尔曲线命令以字母C开头,后跟三对坐标x1,y1 x2,y2 x,y:
x1,y1:起始控制点坐标x2,y2:终点控制点坐标x,y:结束锚点的坐标
需要注意:
- 起始锚点坐标由上一个命令给出。
- 结束锚点坐标来自原始点数组。
- 现在我们必须找到两个控制点的位置。
找到控制点的位置
我们用一条线将起始锚点和结束锚点周围的锚点连接起来(我们将其称为"对立线"):
为了使线条平滑,每个控制点的位置必须相对于其"对立线":
- 控制点位于与"对立线"平行且与当前锚点相切的线上。
- 在该切线上,从锚点到控制点的距离取决于"对立线"的长度和任意"平滑比"。
- 起始控制点与"对立线"的方向相同,而结束控制点则向后。
首先,找到"对立线"属性的函数:
// Properties of a line
// I: - pointA (array) [x,y]: coordinates
// - pointB (array) [x,y]: coordinates
// O: - (object) { length: l, angle: a }: properties of the line
const line = (pointA, pointB) => {
const lengthX = pointB[0] - pointA[0];
const lengthY = pointB[1] - pointA[1];
return {
length: Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2)),
angle: Math.atan2(lengthY, lengthX)
};
};
然后,找到控制点位置的函数:
// Position of a control point
// I: - current (array) [x, y]: current point coordinates
// - previous (array) [x, y]: previous point coordinates
// - next (array) [x, y]: next point coordinates
// - reverse (boolean, optional): sets the direction
// O: - (array) [x,y]: a tuple of coordinates
const controlPoint = (current, previous, next, reverse) => {
// When 'current' is the first or last point of the array
// 'previous' or 'next' don't exist.
// Replace with 'current'
const p = previous || current;
const n = next || current;
// The smoothing ratio
const smoothing = 0.2;
// Properties of the opposed-line
const o = line(p, n);
// If is end-control-point, add PI to the angle to go backward
const angle = o.angle + (reverse ? Math.PI : 0);
const length = o.length * smoothing;
// The control point position is relative to the current point
const x = current[0] + Math.cos(angle) * length;
const y = current[1] + Math.sin(angle) * length;
return [x, y];
};
创建贝塞尔曲线的函数C命令:
// Create the bezier curve command
// I: - point (array) [x,y]: current point coordinates
// - i (integer): index of 'point' in the array 'a'
// - a (array): complete array of points coordinates
// O: - (string) 'C x2,y2 x1,y1 x,y': SVG cubic bezier C command
const bezierCommand = (point, i, a) => {
// start control point
const [cpsX, cpsY] = controlPoint(a[i - 1], a[i - 2], point);
// end control point
const [cpeX, cpeY] = controlPoint(point, a[i - 1], a[i + 1], true);
return `C ${cpsX},${cpsY} ${cpeX},${cpeY} ${point[0]},${point[1]}`;
};
最后,我们重用svgPath函数来循环数组的点并构建<path>元素。然后我们将<path>附加到<svg>元素。
const svg = document.querySelector('.svg');
svg.innerHTML = svgPath(points, bezierCommand);
热门推荐
2025东方卫视跨年晚会:科技与经典的完美融合
双十一钓鱼装备大比拼:调五钓三哪家强?
冬游青岛必打卡:8家超赞海鲜大排档
3种气死人的「无效安慰」方式,很多人都在做
如何安慰你的朋友?15点建议
青岛未来一周最佳出行攻略:避开返程高峰!
新作票房破15亿!“熊出没”系列IP何以“长红”十年?
高血压新指南:为什么不再建议使用水银血压计
西安春节美食地图:从回民街吃到小寨!
舌尖上的西安:肉夹馍 vs 羊肉泡馍
孔明之变化神鬼莫测——借东风背后,诸葛亮有着怎样的战略考量?
徐闻至海南:全新轮渡旅程耗时揭秘
《熊出没》从童年客厅到春节必选
职场人必看!这样预防尿路感染
大熊猫饲养的那些冷知识:从食量到环境,再到健康隐患
大熊猫国家公园:70%栖息地的生态保护秘籍
大熊猫人工繁育技术取得重大突破,728只圈养大熊猫种群遗传多样性得到保障
多元化投资:股市风险管理的利器
财报分析实战指南:从三大报表到潜力股挖掘
秋冬护心小贴士:如何正确使用依折麦布?
杨仪与魏延:蜀汉内部的水火不容
诸葛亮真的不会骑马吗?从史料看“卧龙先生”的真实形象
蜀汉阵营有十大良将,除五虎上将外,另外5人实力强大却鲜为人知
魏延之死与蜀汉命运:历史的假设与现实的反思
信用卡还款协议陷阱大揭秘!
运动有助青少年释放学习压力
《真话坐垫》:一个神奇坐垫引发的春晚爆笑时刻
安徽卫视独播剧场经典再现:《我的野蛮婆婆》与《王子变青蛙》的走红之路
大豆磷脂胶囊:降脂护肝又健脑,科学服用是关键
辛瓦尔小遗孀:如何走出心理阴霾?