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\]