課程介紹
HTML5 CANVAS制圖 基礎(chǔ)總結(jié)
一、基本繪圖
首先,定義2D渲染變量ct(這里用了Jquery庫):va$(#canvasId).get(0).getContext('2d');以下是繪制各種基本圖形的方法:
復(fù)制代碼
//繪制矩形(填充/描框)
ct.fillRect(x,y,w,h)
ct.strokeRect(x,y,w,h)
//繪制路徑--線條
ct.beginPath();
ct.moveTo(x0,y0);
ct.lineTo(x1,y1);
ct.closePath();
ct.stroke();
//繪制路徑--圓弧
ct.beginPath();
ct.arc(x,y,r,start,end,true);
ct.closePath();
ct.fill();
//繪制文本
ct.font = "30px serif...";
ct.fillText(txt,x,y);
ct.strokeText(txt,x,y);
//設(shè)置樣式
ct.fillStyle = "rgb(r,g,b)";
ct.strokeStyle = "rgb()";
ct.lineWidth = 5;
復(fù)制代碼
還提供了一些靈活的方法:
//橡皮擦(擦除矩形范圍)
ct.clearRect(x,y,w,h);
//重置樣式
canvas.attr("width",w);
二、高級(jí)功能
以下是對(duì)畫布的一些變換操作:
復(fù)制代碼
ct.save()/restore() //保存/恢復(fù)
ct.translate(x,y) //平移
ct.scale(a,b) //放大、縮小
ct.rotate(Math.PI) //繞(0,0)旋轉(zhuǎn)
//變換矩陣
ct.transform(xScale,ySkew,xSkew,yScale,xTrans,yTrans)
ct.setTransform(xScale,ySkew,xSkew,yScale,xTrans,yTrans) //重置
復(fù)制代碼
關(guān)于變換矩陣,有一篇很好的文章可以加深你的理解:http://shawphy.com/2011/01/transformation-matrix-in-front-end.html
這是些常用的操作:
復(fù)制代碼
ct.globalAlpha = 0.5 //透明度
//陰影
ct.shadowBlur = 20; //擴(kuò)散
ct.shadowOffsetX = 10;
ct.shadowOffsetY = 10;
ct.shadowColor = rgba;
//漸變(線性/放射性)
ct.createLinearGradient(x,y,x1,y1)
ct.createRadialGradient(x,y,r,x1,y1,r1)
//設(shè)漸變的始終顏色
addColorStop(0,"rgb()")/(1,"rgb()");
復(fù)制代碼
貝塞爾曲線繪制:
//最后兩個(gè)參數(shù)是終點(diǎn)的坐標(biāo)點(diǎn)
ct.beginPath();
ct.moveTo(50,250);
ct.quadraticCurveTo(250,100,450,250) //兩次貝塞爾曲線
ct.bezierCurveTo(150,50,350,450,450,250) //三次貝塞爾曲線
ct.stroke();
畫布導(dǎo)出為圖像:
//生成圖片的src地址
var imgURL = canvas.get(0).toDataURL();
//以下將畫布替換為圖片
var img = $("<img></img>");
img.attr("src",imgURL);
canvas.replaceWith(img);