canvas
**1 由像素點(diǎn)構(gòu)成,位圖,放大會(huì)失真;
2 h5新標(biāo)簽,只兼容高版本瀏覽器;
3 沒有屬性,沒有事件,要結(jié)合js使用;
4 性能高
**
- line
var canvas = document.getElementById('');
var gc = canvas.getContext('2d');
gc.beginPath();
gc.moveTo(x,y);
gc.lineTo(x,y);
....
gc.closePath();
gc.lineWidth=10;
gc.lineCap='round';
gc.lineJoin='bevel';
gc.strokeStyle = 'grey';
gc.stroke();
??!注意:線寬、顏色等設(shè)置一定要在stroke之前寫;
lineCap是線條端點(diǎn)的樣式,默認(rèn)為butt,還可以設(shè)置round|square;
lineJoin是線條連接點(diǎn)的樣式,默認(rèn)為miter,還可以設(shè)置round|bevel。
- 矩形
gc.fillRect(x,y,w,h);
gc.strokeRect(x,y,w,h);
gc.clearRect(0,0,canvas.width,canvas.height);
- 圓形
gc.arc(cx,cy,r,start,end,false);
gc.fillStyle='yellow';
gc.stroke();
?。∽⒁猓浩鹗己徒Y(jié)束的都是弧度,不是角度,要轉(zhuǎn)換(360度是2PI);
false為設(shè)置是否是逆時(shí)針繪制,通常為否;
圓形的繪制默認(rèn)是從右側(cè)開始。
- 文字
gc.font ='20px 微軟雅黑';
var str='繪制文字';
gc.textBaseline='top';
gc.textAlign='center';
gc.strokeText(str,x,y);
?。∽⒁猓豪L制文字textBaseline默認(rèn)是baseline,還可以設(shè)置top|middle|bottom。
- 導(dǎo)出圖片
var str=canvas.toDataURL();
var oImg=new Image();
oImg.src=str;
父級(jí).appendChild(oImg);
??!注意:toDataURL返回的是base64編碼的圖片資源。
- 給canvas添加事件
1 矩形/圓形:通過判斷鼠標(biāo)坐標(biāo)是否在區(qū)域內(nèi),檢測(cè)區(qū)域,添加事件
2 其他不規(guī)則圖形:(返回值是boolean)
gc.isPointInPath(ev.clientX,ev.clientY);