HTML5 Canvas 教程:四、路徑
四、路徑 Paths
4.1路徑 Path
在HTML5畫布上繪製路徑,可以通過連線多個子路徑(曲線)實現。每個子路徑的結束點成為新的路徑的上下文點。我們可以使用lineTo()、arcTo()、quadraticCurveTo()和bezierCurveTo()方法來繪製每個子路徑。每次開始繪製一個新的路徑時,也可以使用beginPath()方法。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext(
context.beginPath();
context.moveTo(100, 20);
// line 1
context.lineTo(200, 160);
// quadratic curve
context.quadraticCurveTo(230, 200, 250, 120);
// bezier curve
context.bezierCurveTo(290, -40, 300, 200, 400, 150);
// line 2
context.lineTo(500, 90);
context.lineWidth = 5;
context.strokeStyle = 'blue';
context.stroke();
</script>
</body>
</html>
以上程式碼演示了通過呼叫不同的曲線繪製方法,繪製路徑。
4.2連線線 Line Join
若要設定HTML5畫布路徑的連線線樣式,可以設定lineJoin上下文屬性。路徑有三種連線樣式:miter、round和bevel。除非另有宣告,否則HTML5畫布連線線預設為斜接樣式。
注意:如果你的線條相當薄,不以陡峭的角度連線,那麼很難區分不同的線條連線。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// set line width for all lines
context.lineWidth = 25;
// miter line join (left)
context.beginPath();
context.moveTo(99, 150);
context.lineTo(149, 50);
context.lineTo(199, 150);
context.lineJoin = 'miter';
context.stroke();
// round line join (middle)
context.beginPath();
context.moveTo(239, 150);
context.lineTo(289, 50);
context.lineTo(339, 150);
context.lineJoin = 'round';
context.stroke();
// bevel line join (right)
context.beginPath();
context.moveTo(379, 150);
context.lineTo(429, 50);
context.lineTo(479, 150);
context.lineJoin = 'bevel';
context.stroke();
</script>
</body>
</html>
以上程式碼演示了在畫布上繪製三種連線線樣式。
4.3圓角 Rounded Corners
使用HTML5的canvas繪製圓角,可以呼叫arcTo()方法,通過定義一個控制點,一個結束點,和半徑繪製一個圓弧,在圓弧的兩端繪製兩條直線。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 200;
var rectHeight = 100;
var rectX = 189;
var rectY = 50;
var cornerRadius = 50;
context.beginPath();
context.moveTo(rectX, rectY);
context.lineTo(rectX + rectWidth - cornerRadius, rectY);
context.arcTo(rectX + rectWidth, rectY, rectX +
rectWidth, rectY + cornerRadius, cornerRadius);
context.lineTo(rectX + rectWidth, rectY + rectHeight);
context.lineWidth = 5;
context.stroke();
</script>
</body>
</html>
以上程式碼演示了在畫布上繪製圓角。