基礎知識
beginPath()新建一條路徑,生成之後,圖形繪製命令被指向到路徑上生成路徑。
closePath()閉合路徑之後圖形繪製命令又重新指向到上下文中。
stroke()通過線條來繪製圖形輪廓。
fill()通過填充路徑的內容區域生成實心的圖形。
lineTo(x, y)繪製一條從當前位置到指定x以及y位置的直線
arc(x, y, radius, startAngle, endAngle, anticlockwise)畫一個以(x,y)爲圓心的以radius爲半徑的圓弧(圓),從startAngle開始到endAngle結束,按照anticlockwise給定的方向(默認爲順時針)來生成
fillStyle = color設置圖形的填充顏色。
strokeStyle = color設置圖形輪廓的顏色。
createLinearGradient(x1, y1, x2, y2)createLinearGradient 方法接受 4 個參數,表示漸變的起點 (x1,y1) 與終點 (x2,y2)
實例1
const chart1 = document.getElementById('canvas');
let ctx = chart1.getContext('2d');
// 三角
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(50,10);
ctx.lineTo(50,50);
ctx.lineTo(10,10);
ctx.strokeStyle = '#b18ea6';
ctx.lineWidth = 2;
ctx.stroke();
ctx.closePath();
// 矩形
ctx.fillStyle = "#00f";
ctx.fillRect(70,10,40,40);
// 扇形
ctx.beginPath();
ctx.moveTo(130, 10);
ctx.arc(130, 10, 40, Math.PI / 4, Math.PI / 2, false);
let grd = ctx.createLinearGradient(130, 10, 150, 50);
grd.addColorStop(0, '#f00');
grd.addColorStop(1, '#0ff');
ctx.fillStyle = grd;
ctx.fill();
ctx.closePath();
fillText(text, x, y [, maxWidth])在指定的(x,y)位置填充指定的文本,繪製的最大寬度是可選的.
strokeText(text, x, y [, maxWidth])在指定的(x,y)位置繪製文本邊框,繪製的最大寬度是可選的.
實例2
ctx.font = "28px serif";
ctx.textAlign = "center";
ctx.fillText("canvas", 100, 100);
ctx.strokeText("canvas", 100, 130);