首先使用canvas寫一個畫布元素,然后獲取到該元素,然后通過getContext('2d') 建立一個 2d 畫布的對象,然后通過該對象的 beginPath() , moveTo(), lineTo(), fill() 等方法開始繪制填充三角形。填充的方式用ctx.fillStyle = '#00ff00' 即可。
好了,話不多說上代碼,,,,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas畫三角形</title>
</head>
<body>
<canvas id="sanjiao"></canvas>
</body>
<script>
var ctx = document.getElementById('sanjiao').getContext("2d");
ctx.beginPath();
ctx.moveTo(100, 0);
ctx.lineTo(0, 100);
ctx.lineTo(0, 0);
ctx.fillStyle = '#00ff00'
// ctx.closePath(); // 可選步驟,關(guān)閉繪制的路徑
// fill 做填充
ctx.fill();
// stroke 加邊框,需和 closePath 配合使用
// ctx.stroke();
</script>
</html>