Canvas的變換的相關內容主要是從平移(translate)、旋轉(rotate)、縮放(scale)、矩陣變換(Tramsform)、陰影(Shadow)、畫布合成和路徑裁剪(Clip)多個方面拓展了Canvas的繪圖能力。css
translate(x,y); // x 左右偏移量,y 上下偏移量
rotate(angle); // 順時針
//接收兩個參數,x,y(x,y > 0),它的本質是一個像素比 scale(x,y);
transform(a,b,c,d,e,f), 一共接收六個參數,在官方文檔中,六個參數分別對應的是:水平縮放,水平傾斜,垂直傾斜,垂直縮放,水平平移以及垂直平移。html
下面是3*3 的矩陣圖:css3
a c e b d f 0 0 1
實現transform只須要來解矩陣就能夠了。不管是html仍是canvas,全部的變換都是由一個點來完成的,由於圖像自己就是由點構成的。`x' = a*x + c*y + 1*e`,`y' = b*x + d*y + 1*f`。canvas
transform(1,0,0,1,100,100); translate(100,100);
數組
transform(0.5, 0, 0, 0.5, 0, 0); scale(0.5, 0.5);
網站
transform(cosθ, sinθ, -sinθ, cosθ, 0, 0); rotate(θ);
.net
一共有四個參數:code
shadowOffsetX,陰影橫向位移量orm
shadowOffsetY,陰影縱向位移量htm
shadowColor,陰影顏色
shadowBlur,陰影模糊範圍
/\* Shadow */ ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.shadowColor = '#595959'; ctx.shadowBlur = 2; /\* Text */ ctx.font = "100px sans-serif"; ctx.fillText("俠課島", 10, 400);
source-over - 目標圖像上顯示源圖像 - 默認屬性
source-atop - 源圖像位於目標圖像以外部分不可見
source-in - 顯示目標圖像以內的源圖像部分, 目標圖像透明
source-out - 顯示目標圖像以外的源圖像部分, 目標圖像透明
destination-over - 源圖像上顯示目標圖像
destination-atop - 源圖像頂部顯示目標圖像。目標圖像位於源圖像以外的部分不可見
destination-in - 源圖像中顯示目標圖像。只顯示源圖像以內的目標圖像部分, 源圖像透明
destination-out - 源圖像以外顯示目標圖像。只顯示源圖像以外的目標圖像部分, 源圖像是透明的
darken - 保證重疊部分最暗(16進制數值最大)的像素
lighter - 保證重疊部分最亮(16進制數值最小)的像素
copy - 只保留目標圖像
xor - 源圖像與目標圖像重疊部分透明
如圖:
// 接收一個數組,和context上下文 const polygon = (poly, context) => { context.beginPath(); context.moveTo(poly\[0\], poly\[1\]); for (var i = 2; i <= poly.length - 2; i += 2) { context.lineTo(poly\[i\], poly\[i + 1\]); } context.closePath(); context.stroke(); } const canvas = document.getElementById('canvas'); /* 得到 2d 上下文對象 */ const ctx = canvas.getContext('2d'); const pointList = \[300, 0, 366, 210, 588, 210, 408, 342, 474, 546, 300, 420, 126, 546, 192, 342, 12, 210, 234, 210\]; polygon(pointList, ctx); ctx.clip(); const img = new Image(); img.src = "./logo.png"; img.onload = () => { const pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.drawImage(img, 0, 0, 610, 610); }
提供一個網站地址:tools.jb51.net/code/css3path,代碼中的[300, 0, 366, 210, 588, 210, 408, 342, 474, 546, 300, 420, 126, 546, 192, 342, 12, 210, 234, 210]這一串數字咱們能夠在網站中獲取拿到它繪製的百分比,而後複製到控制檯,去掉百分號轉換成具體的數值,而後賦給一個數組,而後array.map,而後根據寬度的多少,每個都乘以它。假設是一個五角星,以下圖所示:
const array = \[50, 0, 61, 3, 98, 35, 68, 57, 79, 91, 50, 70, 21, 91, 32, 57, 2, 35, 39, 35\]; array.map(s => s * 6); // \[300, 0, 366, 210, 588, 210, 408, 342, 474, 546, 300, 420, 126, 546, 192, 342, 12, 210, 234, 210\]