html5 – 在HTML 5 2d Canvas上下文中查找曲线上的点

给定由2d画布上下文函数bezierCurveto,quadraticCurveto或arcTo绘制的线条,如何沿这些线条找到点?

我的目的是在曲线的中点绘制一个物体.使用SVG DOM,我可以使用方法getPointAtLength& getTotalLength,但我看不到HTML画布中的等价物.

解决方法

你发现他们很难:(

HTML画布中没有等效的东西.你必须用简单的旧数学自己找到中点.

我做了一个如何为你找到贝塞尔曲线中点的例子.在jsfiddle here上看到它.下面粘贴了一个javascript的副本.

实曲线为红色,中点为微小的绿色矩形.其他一切只是一种视觉辅助.

var ctx = $("#test")[0].getContext("2d")
function mid(a,b) {
 return (a+b) / 2;
}


var cp1x = 100;
var cp1y = 150;
var cp2x = 175;
var cp2y = 175;
var x = 200;
var y = 0;

ctx.linewidth = 4;
ctx.strokeStyle = "red";
ctx.fillStyle = "rgba(0,0.6)";

ctx.beginPath();
ctx.moveto(0,0);
ctx.bezierCurveto(cp1x,cp1y,cp2x,cp2y,x,y);
ctx.stroke();

//line goes from start to control point 1
ctx.strokeStyle = "rgba(0,200,0.4)";
ctx.beginPath();
ctx.moveto(0,0);
ctx.lineto(cp1x,cp1y);
ctx.stroke();

//line goes from end to control point 2
ctx.beginPath();
ctx.moveto(x,y);
ctx.lineto(cp2x,cp2y);
ctx.stroke();

//line goes from control point to control point
ctx.strokeStyle = "rgba(200,0.4)";
ctx.beginPath();
ctx.moveto(cp1x,cp1y);
ctx.lineto(cp2x,cp2y);
ctx.stroke();

// Now find the midpoint of each of those 3 lines
var ax = mid(cp1x,0);
var bx = mid(cp2x,x)
var cx = mid(cp1x,cp2x)

var ay = mid(cp1y,0)    
var by = mid(cp2y,y)    
var cy = mid(cp1y,cp2y)


// draw midpoints for visual aid 
// not gonna look exact 'cause square
// will be drawn from top-right instead of center
ctx.fillRect(ax,ay,4,4);
ctx.fillRect(bx,by,4);
ctx.fillRect(cx,cy,4);


//Now draw lines between those three points. These are green
ctx.strokeStyle = "rgba(0,0.4)";
ctx.beginPath();
ctx.moveto(ax,ay);
ctx.lineto(cx,cy);
ctx.stroke();

ctx.beginPath();
ctx.moveto(bx,by);
ctx.lineto(cx,cy);
ctx.stroke();

//Now the midpoint of the green lines:
// so g1 and g2 are the green line midpoints
var g1x = mid(ax,cx);
var g2x = mid(bx,cx);

var g1y = mid(ay,cy); 
var g2y = mid(by,cy);  

//draw them to make sure:
ctx.fillRect(g1x,g1y,4);
ctx.fillRect(g2x,g2y,4);

//Now one final line,in gray
ctx.strokeStyle = "rgba(20,20,0.4)";
ctx.beginPath();
ctx.moveto(g1x,g1y);
ctx.lineto(g2x,g2y);
ctx.stroke();

//whew! We made it!
var FinallyTheMidpointx = mid(g1x,g2x); 
var FinallyTheMidpointy = mid(g1y,g2y); 

//draw something at the midpoint to celebrate
ctx.fillStyle = "rgba(0,255,1)";
ctx.fillRect(FinallyTheMidpointx,FinallyTheMidpointy,4);

相关文章

HTML5和CSS3实现3D展示商品信息的代码
利用HTML5中的Canvas绘制笑脸的代码
Html5剪切板功能的实现
如何通过HTML5触摸事件实现移动端简易进度条
Html5移动端获奖无缝滚动动画实现
关于HTML5和CSS3实现机器猫的代码