问题描述
对于绘图应用程序,我将鼠标移动坐标保存到数组,然后用lineTo绘制它们。结果线不平滑。如何在所有聚集点之间产生单个曲线?
For a drawing application I'm saving the mouse movement coordinates to an array then drawing them with lineTo. The resulting line is not smooth. How can I produce a single curve between all the gathered points?
我已经google了,但我只找到了3个绘制线的函数:对于2个采样点,只需使用lineTo。对于3个采样点quadraticCurveTo,对于4个采样点,bezierCurveTo。
I've googled but I have only found 3 functions for drawing lines: For 2 sample points, simply use lineTo. For 3 sample points quadraticCurveTo, for 4 sample points, bezierCurveTo.
(我尝试为数组中的每4个点绘制一个bezierCurveTo,但这会导致每4个采样点出现扭结,而不是连续的平滑曲线。)
(I tried drawing a bezierCurveTo for every 4 points in the array, but this leads to kinks every 4 sample points, instead of a continuous smooth curve.)
如何编写一个函数来绘制一个具有5个采样点及以上的平滑曲线?
How do I write a function to draw a smooth curve with 5 sample points and beyond?
推荐答案
连接后续采样点和不相交的curveTo类型函数的问题是, 。这是因为两条曲线共享一个终点,但受完全不相交的控制点的影响。一个解决方案是曲线到接下来的2个随后的采样点之间的中点。使用这些新的内插点连接曲线给出了在端点处的平滑过渡(一次迭代的端点是下一次迭代的控制点)。换句话说,两个不相交的曲线具有
The problem with joining subsequent sample points together with disjoint "curveTo" type functions, is that where the curves meet is not smooth. This is because the two curves share an end point but are influenced by completely disjoint control points. One solution is to "curve to" the midpoints between the next 2 subsequent sample points. Joining the curves using these new interpolated points gives a smooth transition at the end points (what is an end point for one iteration becomes a control point for the next iteration.) In other words the two disjointed curves have much more in common now.
此解决方案是从基础ActionScript 3.0动画:使事情移动一书中提取出来的。 p.95 - 渲染技术:创建多个曲线。
This solution was extracted out of the book "Foundation ActionScript 3.0 Animation: Making things move". p.95 - rendering techniques: creating multiple curves.
注意:这个解决方案实际上并不绘制每个点,这是我的问题的标题近似通过样本点的曲线,但从不通过样本点),但是对于我的目的(绘图应用程序),它对我来说足够好,在视觉上你不能说出差异。 是一种解决方案,可用于浏览所有示例点,但它更复杂(参见)
Note: this solution does not actually draw through each of the points, which was the title of my question (rather it approximates the curve through the sample points but never goes through the sample points), but for my purposes (a drawing application), it's good enough for me and visually you can't tell the difference. There is a solution to go through all the sample points, but it is much more complicated (see http://www.cartogrammar.com/blog/actionscript-curves-update/)
这是近似法的绘图代码:
Here is the the drawing code for the approximation method:
// move to the first point
ctx.moveTo(points[0].x, points[0].y);
for (i = 1; i < points.length - 2; i ++)
{
var xc = (points[i].x + points[i + 1].x) / 2;
var yc = (points[i].y + points[i + 1].y) / 2;
ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
}
// curve through the last two points
ctx.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x,points[i+1].y);
这篇关于如何使用javascript HTML5 canvas绘制平滑曲线通过N点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!