相信在工做中你們都會接觸到canvas的使用,通常狀況下工做中都不會要求畫特別可貴圖形(用到特別難的圖形,大多數選擇插件實現)基於此,咱們學會一些常規的操做,而後結合項目進行一些擴展便可知足要求。html
canvas的畫布是一個H5新增的標籤。canvas
<canvas id="canvas" width="1000" height="600" style="background-color: aliceblue;">您的瀏覽器不支持canvas</canvas>
複製代碼
canvas主要經過js畫圖,接下來咱們詳細講講怎麼畫一些圖形。瀏覽器
class Draw {
constructor(ctx) {
this.ctx = ctx;
}
// 畫圖方法
// ...
}
window.onload = function() {
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const draw = new Draw(ctx);
// 一些畫圖操做
// ...
}
複製代碼
strokeStyle和stroke是成對出現的。markdown
drawLine() {
this.ctx.moveTo(10,10); // 開始位置
this.ctx.lineTo(50, 10);
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = 'red';
this.ctx.stroke();
}
複製代碼
rect和strokeRect效果是同樣的ui
// rect
drawRect() {
this.ctx.strokeStyle = 'red';
this.ctx.strokeRect(10, 50, 40, 20);
this.ctx.fillStyle = 'red';
this.ctx.fillRect(60, 50, 40, 20);
}
複製代碼
上述的參數中,x,y 表示圓心的座標,radius 是半徑,start 開始弧度,end 結束弧度,anticlockwise 表示是不是逆時針。this
畫圓或者弧形的時候要注意,若是沒有beginPath,將會以畫布的最左側爲起始點,圖形以下
複製代碼
// arc
drawArc() {
this.ctx.beginPath();
this.ctx.arc(100, 150, 50, Math.PI * 2, false);
this.ctx.closePath();
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = 'red';
this.ctx.stroke();
this.ctx.fillStyle = 'green',
this.ctx.fill();
}
複製代碼
無spa
drawText() {
this.ctx.fillStyle = 'red';
this.ctx.font = 'bold 40px 微軟雅黑';
this.ctx.fillText('實心文本', 150, 200);
this.ctx.strokeStyle = 'green';
this.ctx.font = 'bold 40px 微軟雅黑';
this.ctx.lineWidth = 1;
this.ctx.strokeText('空心文本', 150, 250)
}
複製代碼
若是以爲對你有幫助,請點贊或評論,我會更新下去插件