想看前面整理的canvas常用API的同學可以點下面:
canvas學習之API整理筆記(一)
canvas學習之API整理筆記(二)
本系列文章涉及的所有代碼都將上傳至:項目代碼github地址,喜歡的同學們歡迎點Star~
從本篇文章開始,我會分享給大家canvas繪制的各種基礎圖形和酷炫的圖形,注意:是一系列!歡迎關注!
后續每篇文章我會着重分享給大家一些使用Canvas開發的實例和這些實例的實現思路。
本文看點:使用canvas來繪制常見的各種圖形實例,並且會簡單封裝一下繪制各圖形的方法,最后會分享給大家一個封裝好的快速繪制多邊形的方法。
開始之前
//獲取canvas容器
var can = document.getElementById('canvas');
//創建一個畫布
var ctx = can.getContext('2d');
繪制圓形
var draw = function(x, y, r, start, end, color, type) {
var unit = Math.PI / 180;
ctx.beginPath();
ctx.arc(x, y, r, start * unit, end * unit);
ctx[type + 'Style'] = color;
ctx.closePath();
ctx[type]();
}
參數解釋
:x,y-圓心;start-起始角度;end-結束角度;color-繪制顏色;type-繪制類型('fill'和'stroke')。
實例如下圖所示:
繪制三角形
var draw = function(x1, y1, x2, y2, x3, y3, color, type) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx[type + 'Style'] = color;
ctx.closePath();
ctx[type]();
}
參數解釋
:x1(2、3),y1(2、3)-三角形的三個點的坐標;color-繪制顏色;type-繪制類型('fill'和'stroke')。
實例如下圖所示:
繪制(圓角)矩形
var draw = function(x, y, width, height, radius, color, type){
ctx.beginPath();
ctx.moveTo(x, y+radius);
ctx.lineTo(x, y+height-radius);
ctx.quadraticCurveTo(x, y+height, x+radius, y+height);
ctx.lineTo(x+width-radius, y+height);
ctx.quadraticCurveTo(x+width, y+height, x+width, y+height-radius);
ctx.lineTo(x+width, y+radius);
ctx.quadraticCurveTo(x+width, y, x+width-radius, y);
ctx.lineTo(x+radius, y);
ctx.quadraticCurveTo(x, y, x, y+radius);
ctx[type + 'Style'] = color || params.color;
ctx.closePath();
ctx[type]();
}
參數解釋
:x,y-左上角點的坐標;width、height-寬高;radius-圓角;color-繪制顏色;type-繪制類型('fill'和'stroke')。
實例如下圖所示:
繪制多邊形
var drawPolygon = function(ctx, conf){
var x = conf && conf.x || 0; //中心點x坐標
var y = conf && conf.y || 0; //中心點y坐標
var num = conf && conf.num || 3; //圖形邊的個數
var r = conf && conf.r || 100; //圖形的半徑
var width = conf && conf.width || 5;
var strokeStyle = conf && conf.strokeStyle;
var fillStyle = conf && conf.fillStyle;
//開始路徑
ctx.beginPath();
var startX = x + r * Math.cos(2*Math.PI*0/num);
var startY = y + r * Math.sin(2*Math.PI*0/num);
ctx.moveTo(startX, startY);
for(var i = 1; i <= num; i++) {
var newX = x + r * Math.cos(2*Math.PI*i/num);
var newY = y + r * Math.sin(2*Math.PI*i/num);
ctx.lineTo(newX, newY);
}
ctx.closePath();
//路徑閉合
if(strokeStyle) {
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = width;
ctx.lineJoin = 'round';
ctx.stroke();
}
if(fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
}
參數說明:
ctx: canvas畫布
conf: 配置項,提供以下一些配置
- x: 中心點橫坐標
- y: 中心點縱坐標
- num: 多邊形的邊數
- r:多邊形的半徑長度
- width:多邊形線的寬度
- strokeStyle:邊線的顏色
- fillStyle:填充的顏色
上圖效果的代碼如下:
上圖1的代碼:
drawPolygon(ctx, {
num: 6,
r: 100,
strokeStyle: 'blue',
fillStyle: '#9da'
})
上圖2的代碼:
drawPolygon(ctx, {
num: 4,
r: 150,
strokeStyle: 'red',
width: 4
})
上圖3的代碼:
drawPolygon(ctx, {
x: 800,
y: 250,
num: 10,
fillStyle: '#000'
})
結語
我們總結一下,使用canvas繪制圖形就是那幾個函數:beginPath
、arc
、moveTo
、lineTo
、closePath
、fill
、stroke
。當我們能夠熟練掌握並運用自如的時候,就能夠獨當一面了。加油吧,騷年們!
本文涉及的代碼我已經上傳至github,項目代碼github地址,喜歡的同學點個Star,多謝多謝~