canvas繪製貝塞爾曲線

一、繪製二次方貝塞爾曲線javascript

quadraticCurveTo(cp1x,cp1y,x,y); 其中參數cp1x和cp1y是控制點的座標,x和y是終點座標css

數學公式表示以下:html

二次方貝茲曲線的路徑由給定點P0P1P2的函數Bt)追蹤:java

\mathbf{B}(t) = (1 - t)^{2}\mathbf{P}_0 + 2t(1 - t)\mathbf{P}_1 + t^{2}\mathbf{P}_2 \mbox{ , } t \in [0,1]

<!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

P0P1P2P3四個點在平面或在三維空間中定義了三次方貝茲曲線。曲線起始於P0走向P1,並從P2的方向來到P3。通常不會通過P1P2;這兩個點只是在那裏提供方向資訊。P0P1之間的間距,決定了曲線在轉而趨進P3以前,走向P2方向的「長度有多長」。code

\mathbf{B}(t)=\mathbf{P}_0(1-t)^3+3\mathbf{P}_1t(1-t)^2+3\mathbf{P}_2t^2(1-t)+\mathbf{P}_3t^3 \mbox{ , } t \in [0,1]

<!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>

相關文章
相關標籤/搜索