天天看點

Canvas貝塞爾曲線和二次貝塞爾曲線

貝塞爾曲線和二次曲線

貝塞爾曲線大概就是ps中鋼筆工具那個曲線

quadraticCurveTo(cp1x, cp1y, x, y)

從目前筆位置到由指定的結束點繪制的二次貝塞爾曲線

x

,并

y

使用由指定的控制點

cp1x

cp1y

Canvas貝塞爾曲線和二次貝塞爾曲線

例子:

此示例顯示了如何繪制二次貝塞爾曲線。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
   
</head>

<body onload="draw();">
    <canvas id="canvas" width="400" height="400"></canvas>
</body>
 <script type="application/javascript">
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

//貝塞爾曲線
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.quadraticCurveTo(230, 30, 50, 100);
ctx.stroke();

// 起點和終點
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(50, 20, 5, 0, 2 * Math.PI);   //起始點
ctx.arc(50, 100, 5, 0, 2 * Math.PI);  // 終點
ctx.fill();

// 控制點
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(230, 30, 5, 0, 2 * Math.PI);
ctx.fill();
    </script>
</html>
           

效果圖:

Canvas貝塞爾曲線和二次貝塞爾曲線

二次貝塞爾曲線

文法:

void ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
           
cp1x
           

第一個控制點的x軸坐标。

cp1y
           

第一個控制點的y軸坐标。

cp2x
           

第二個控制點的x軸坐标。

cp2y
           

第二個控制點的y軸坐标。

x
           

終點的x軸坐标。

y
           

終點的y軸坐标。

案例:

繪制一個三次貝塞爾曲線

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
   
</head>

<body onload="draw();">
    <canvas id="canvas" width="400" height="400"></canvas>
</body>
 <script type="application/javascript">
//定義畫布和上下文
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 将點定義為{x,y}
let start = { x: 50,    y: 20  };
let cp1 =   { x: 230,   y: 30  };
let cp2 =   { x: 150,   y: 80  };
let end =   { x: 250,   y: 100 };

// 三次貝塞爾曲線
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y);
ctx.stroke();

// 起始點和終止點
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(start.x, start.y, 5, 0, 2 * Math.PI);  // 起始點
ctx.arc(end.x, end.y, 5, 0, 2 * Math.PI);      // 終止點
ctx.fill();

// 控制點
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI);  // 控制點一
ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI);  // 控制點二
ctx.fill();
    </script>
</html>
           

效果圖:

Canvas貝塞爾曲線和二次貝塞爾曲線

案例二:

渲染語音氣球

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
   
</head>

<body onload="draw();">
    <canvas id="canvas" width="400" height="400"></canvas>
</body>
 <script type="application/javascript">
function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // 二次貝塞爾曲線案例
    ctx.beginPath();
    ctx.moveTo(75, 25);
    ctx.quadraticCurveTo(25, 25, 25, 62.5);
    ctx.quadraticCurveTo(25, 100, 50, 100);
    ctx.quadraticCurveTo(50, 120, 30, 125);
    ctx.quadraticCurveTo(60, 120, 65, 100);
    ctx.quadraticCurveTo(125, 100, 125, 62.5);
    ctx.quadraticCurveTo(125, 25, 75, 25);
    ctx.stroke();
  }
}
    </script>
</html>
           

效果圖:

Canvas貝塞爾曲線和二次貝塞爾曲線