初探canvas

進擊的奧特曼發表於2018-06-27

首先是什麼原因接觸這個技術棧呢,
首先產品突然來個需求,說要點選按鈕下載一個海報圖,提供背景圖,背景圖上的資料是後端返回, 一開始告訴產品,不能實現,然後另一個前端同事說可以用canvas做到,一臉懵逼的我(我擦,還有這種操作,還是知識面不夠廣啊,然後趕緊去度娘研究)

定義ctx物件

let cvs = document.createElement('canvas');
let ctx = cvs.getContext('2d');
我是在頁面上定義了一個canvas標籤,id為canvas
這個是所有開始畫canvas必須做的,getContext() 方法返回一個用於在畫布上繪圖的環境。

設定下載圖的寬高

cvs.width = 1240;
cvs.height =1753;
這個比較簡單,跟html差不多

設定背景圖

var img=document.getElementById("scream");
ctx.drawImage(img,0,0);
在html寫個img標籤,id為scream,src為你要的圖片地址
這個也比較簡單,drawImage方法接收3個引數,第二,第三個引數為離左上角的距離

畫圓角矩形

個人覺得這個點是畫圖最難的一個點,百度了很多,但是沒找到有直接畫矩形帶設定類似html border-radius的api,然後去百度啊,經過朋友的幫忙,找到了一個封裝的方法,如下
引數說明:

ctx:ctx物件,這個沒什麼好說 x:離x軸的距離
y: 離y軸的距離
width:矩形的寬
height:矩形的高
radius:類似css的border-radius屬性,值為數字
fill:是否填充背景,值為true或者false
stroke:是否有邊框陰影,值為true或者false
function strokeRoundRect(ctx, x, y, width, height, radius, fill, stroke,fillStyle){
if (typeof stroke == 'undefined') {
stroke = true;
}
if (typeof radius === 'undefined') {
radius = 5;
}
if (typeof radius === 'number') {
radius = {tl: radius, tr: radius, br: radius, bl: radius};
} else {
var defaultRadius = {tl: 0, tr: 0, br: 0, bl: 0};
for (var side in defaultRadius) {
radius[side] = radius[side] || defaultRadius[side];
}
} ctx.beginPath();
ctx.moveTo(x + radius.tl, y);
ctx.lineTo(x + width - radius.tr, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
ctx.lineTo(x + width, y + height - radius.br);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
ctx.lineTo(x + radius.bl, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
ctx.lineTo(x, y + radius.tl);
ctx.quadraticCurveTo(x, y, x + radius.tl, y);
ctx.fillStyle=fillStyle;
ctx.closePath();
if (fill) {
ctx.fill();
}
if (stroke) {
ctx.stroke();
}
}

畫倒三角形

ctx.beginPath
var height = 60*Math.sin(Math.PI/3);//計算等邊三角形的高
ctx.moveTo(620,1220); //從哪個座標開始畫
ctx.lineTo(590,height+1120);//B點,從A(100,0)開始,畫到B 點結束
ctx.lineTo(650,height+1120); //C點,B座標到C座標
ctx.fillStyle='#fff';//背景色設定白色
ctx.fill(); //閉合形狀並且以填充方式繪製出來

設定文字

ctx.font="47px 思源黑體";
ctx.fillStyle ="#f0d748";
ctx.textAlign = 'center';
ctx.textBaseline='middle';//文字垂直方向,基線位置
ctx.fillText("文字",620,292);

總結

canvas一定要按順序畫,不然後面的會覆蓋前面的內容,用canvas,感覺畫座標除錯很麻煩, emmmmmm。。。從此不想再碰canvas的心都有

第一次在掘金寫文章,比較簡短,如有不足,請各位大佬多提下意見~~~