今天帶大家學(xué)習(xí)用js繪畫(canvas),首先呢先學(xué)習(xí)canvas的基礎(chǔ)知識。
我們通常畫畫得需要一張紙或者一個(gè)畫板,所以js畫畫也得需要一張畫布
首先創(chuàng)建獲取畫布;
然后再獲取2d
var ctx = canavs.getContext('2d');
- 開新路徑
ctx.beginPath();
起始點(diǎn)
x是橫坐標(biāo),y是縱坐標(biāo)
ctx.moveTo(x, y);路徑
x是橫坐標(biāo),y是縱坐標(biāo)
ctx.lineTo(x, y)閉合路徑
ctx.closePath()描邊與填充
ctx.stroke();
ctx.fill();設(shè)置描邊和填充的顏色
ctx.strokeStyle = '顏色';
ctx.fillStyle = '顏色';清除畫布
ctx.clearRect(x, y, width, height);
線的樣式
線的寬度
ctx.lineWidth = 線的寬度線帽
ctx.lineCap = 'butt'//默認(rèn)的
round: 半圓
square: 方形
圓
圓心:x, y是坐標(biāo)
blur: 半徑
start,end: 起始角度,結(jié)束角度
boolean: 是否為逆時(shí)針(true), 默認(rèn)順時(shí)針(false))
ctx.arc(x, y, blur, start, end, boolean)
保存狀態(tài)
ctx.save(); // 保存當(dāng)前的狀態(tài)
ctx.restore(); // 返回上一級狀態(tài)
- 填充矩形
x, y是坐標(biāo)
寬高:width, height
ctx.fillRect(x, y, width, height);
- 繪制矩形路徑
寬高:width, height
ctx.rect(x, y, width, height)
- 弧形
參考點(diǎn)1坐標(biāo): x1, y1
參考點(diǎn)2坐標(biāo): x2, y2
所切選圓的半徑:r
ctx.arcTo(x1, y1, x2, y2, r);
- 填充字體
content: 字體內(nèi)容
ctx.fillText(content, x, y)
- 描邊字體
content: 字體內(nèi)容
ctx.strokeText(content, x, y);
- 文本垂直居中
ctx.textBaseline = 'middle'; // top // bottom
- 文本水平居中
ctx.textAlign = 'center'; // left // right