一、繪製二次方貝塞爾曲線javascript
quadraticCurveTo(cp1x,cp1y,x,y); 其中參數cp1x和cp1y是控制點的座標,x和y是終點座標css
數學公式表示以下:html
二次方貝茲曲線的路徑由給定點P0、P1、P2的函數B(t)追蹤:java
<!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>
二、三次方貝塞爾曲線canvas
bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y) 其中參數cp1x,cp1y表示第一個控制點的座標, cp2x,cp2y表示第二個控制點的座標, x,y是終點的座標;函數
數學公式表示以下:spa
P0、P1、P2、P3四個點在平面或在三維空間中定義了三次方貝茲曲線。曲線起始於P0走向P1,並從P2的方向來到P3。通常不會通過P1或P2;這兩個點只是在那裏提供方向資訊。P0和P1之間的間距,決定了曲線在轉而趨進P3以前,走向P2方向的「長度有多長」。code
<!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>