贝塞尔实例
Bezier and quadratic curves
*1 quadraticCurveTo(cp1x, cp1y, x, y)://cpx,cpy表示控制点的坐标, x,y表示终点坐标;
数学公式表示如下:
二次方贝兹曲线的路径由给定点P0、P1、P2的函数B(t)追踪:
代码实例:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>canvas直线</title> 6 <meta name="Keywords" content=""> 7 <meta name="author" content="@my_programmer"> 8 <style type="text/css"> 9 body, h1{margin:0;} 10 canvas{margin: 20px;} 11 </style> 12 </head> 13 <body onload="draw()"> 14 <h1>二次贝塞尔曲线</h1> 15 <canvas id="canvas" width=200 height=200 style="border: 1px solid #ccc;"></canvas> 16 <script> 17 function draw() { 18 var canvas=document.getElementById('canvas'); 19 var context=canvas.getContext('2d'); 20 //绘制起始点、控制点、终点 21 context.beginPath(); 22 context.moveTo(20,170); 23 context.lineTo(130,40); 24 context.lineTo(180,150); 25 context.stroke(); 26 27 //绘制2次贝塞尔曲线 28 context.beginPath(); 29 context.moveTo(20,170); 30 context.quadraticCurveTo(130,40,180,150); 31 context.strokeStyle = "red"; 32 context.stroke(); 33 } 34 </script> 35 </body> 36 </html>
代码效果:
*2 bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)://cp1x,cp1y表示第一个控制点的坐标, cp2x,cp2y表示第二个控制点的坐标, x,y表示终点的坐标;
数学公式表示如下:
P0、P1、P2、P3四个点在平面或在三维空间中定义了三次方贝兹曲线。曲线起始于P0走向P1,并从P2的方向来到P3。一般不会经过P1或P2;这两个点只是在那里提供方向资讯。P0和P1之间的间距,决定了曲线在转而趋进P3之前,走向P2方向的“长度有多长”。
代码实例:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>canvas直线</title> 6 <meta name="Keywords" content=""> 7 <meta name="Description" content=""> 8 <style type="text/css"> 9 body, h1{margin:0;} 10 canvas{margin: 20px; } 11 </style> 12 </head> 13 <body onload="draw()"> 14 <h1>三次贝塞尔曲线</h1> 15 <canvas id="canvas" width=200 height=200 style="border: 1px solid #ccc;"></canvas> 16 <script> 17 function draw() { 18 var canvas=document.getElementById('canvas'); 19 var context=canvas.getContext('2d'); 20 //绘制起始点、控制点、终点 21 context.beginPath(); 22 context.moveTo(25,175); 23 context.lineTo(60,80); 24 context.lineTo(150,30); 25 context.lineTo(170,150); 26 context.stroke(); 27 28 //绘制3次贝塞尔曲线 29 context.beginPath(); 30 context.moveTo(25,175); 31 context.bezierCurveTo(60,80,150,30,170,150); 32 context.strokeStyle = "red"; 33 context.stroke(); 34 } 35 </script> 36 </body> 37 </html>
代码效果图: