1、繪制二次方貝塞爾曲線
quadraticCurveTo(cp1x,cp1y,x,y); 其中參數cp1x和cp1y是控制點的坐標,x和y是終點坐標
數學公式表示如下:
二次方貝茲曲線的路徑由給定點P0、P1、P2的函數B(t)追蹤:
<!DOCTYPE html> <Html> <head> <meta charset="utf-8"> <title></title> <style type="text/CSS"> *{padding: 0;margin:0;} body{background: #1b1b1b;} #div1{margin:50px auto; width:300px; height: 300px;} canvas{background: #fff;} </style> <script type="text/Javascript"> window.onload = function(){ var c = document.getElementById("myCanvas"); var content = c.getContext("2d"); //繪制二次方貝塞爾曲線 content.strokeStyle ="#FF5D43"; content.beginPath(); content.moveTo(0,200); content.quadraticCurveTo(75,50,300,200); content.stroke(); content.globalCompositeOperation = "source-over"; //目標圖像上顯示源圖像 //繪制上面曲線的控制點和控制線,控制點坐標為兩直線的交點(75,50) content.strokeStyle = "#f0f"; content.beginPath(); content.moveTo(75,50); content.lineTo(0,200); content.moveTo(75,50); content.lineTo(300,200); content.stroke(); }; </script> </head> <body> <div id="div1"> <canvas id="myCanvas" width="300" height="200"></canvas> </div> </body> </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方向的“長度有多長”。
<!DOCTYPE html> <Html> <head> <meta charset="utf-8"> <title></title> <style type="text/CSS"> *{padding: 0;margin:0;} body{background: #1b1b1b;} #div1{margin:50px auto; width:300px; height: 300px;} canvas{background: #fff;} </style> <script type="text/Javascript"> window.onload = function(){ var c = document.getElementById("myCanvas"); var content = c.getContext("2d"); //三次方貝塞爾曲線 content.strokeStyle = "#FA7E2A"; content.beginPath(); content.moveTo(25,175); content.bezIErCurveTo(60,80,150,30,170,150); content.stroke(); content.globalCompositeOperation = "source-over"; //繪制起點、控制點、終點 content.strokeStyle = "red"; content.beginPath(); content.moveTo(25,175); content.lineTo(60,80); content.lineTo(150,30); content.lineTo(170,150); content.stroke(); }; </script> </head> <body> <div id="div1"> <canvas id="myCanvas" width="300" height="200"></canvas> </div> </body> </Html>