一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情。
在上一篇文章中我们学习了canvas的基本使用,本文继续学习canvas的进阶概念。我们一起看看吧!
canvas的概念
Canvas 颜色样式和阴影
设置填充和描边的颜色
- fillStyle : 设置或返回用于填充绘画的颜色
- strokeStyle: 设置或返回用于笔触的颜色
ctx.strokeStyle = 'red';
ctx.strokeStyle = '#ccc';
ctx.strokeStyle = 'rgb(255,0,0)';
ctx.strokeStyle = 'rgba(255,0,0,6)';
变换
缩放
scale()方法缩放当前绘图,更大或更小
context.scale(scalewidth,scaleheight)
- scalewidth : 缩放当前绘图的宽度 (1=100%, 0.5=50%, 2=200%)
- scaleheight : 缩放当前绘图的高度 (1=100%, 0.5=50%, 2=200%) 注意:缩放的是整个画布,缩放后,继续绘制的图形会被放大或缩小。
位移画布
- ctx.translate(x,y) 方法重新映射画布上的 (0,0) 位置
- 参数说明:
- x: 添加到水平坐标(x)上的值
- y: 添加到垂直坐标(y)上的值
- 发生位移后,相当于把画布的 0,0 坐标 更换到新的 x,y 的位置,所有绘制的新元素都被影响。 位移画布一般配合缩放和旋转等。
旋转
context.rotate(angle);方法旋转当前的绘图- 注意参数是弧度(PI)
- 如需将角度转换为弧度,请使用 degrees*Math.PI/180 公式进行计算。
绘制环境保存和还原
- ctx.save()
- ctx.restore()
画布保存 base64 编码内容
- 把 canvas 绘制的内容输出成 base64 内容。
- 语法:canvas.toDataURL(type, encoderOptions);
- 参数说明:
- type,设置输出的类型,比如 image/png image/jpeg 等
- encoderOptions: 0-1 之间的数字,用于标识输出图片的质量,1 表示无损压缩,类型为: image/jpeg 或者 image/webp 才起作用。 举个栗子:
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
var img = document.querySelector("#img-demo");
img.src = canvas.toDataURL("image/png");
画布渲染画布
- context.drawImage(img,x,y);
- img 参数也可以是画布,也就是把一个画布整体的渲染到另外一个画布上。
var canvas1 = document.querySelector('#cavsElem1');
var canvas2 = document.querySelector('#cavsElem2');
var ctx1 = canvas1.getContext('2d');
var ctx2 = canvas2.getContext('2d');
ctx1.fillRect(20, 20, 40, 40); // 在第一个画布上绘制矩形
ctx2.drawImage(canvas1, 10, 10); // 将第一个画布整体绘制到第二个画布上
线条样式
lineCap 设置或返回线条的结束端点(线头、线冒)样式
- butt : 默认。向线条的每个末端添加平直的边缘。
- round : 向线条的每个末端添加圆形线帽。
- square: 向线条的每个末端添加正方形线帽。
Canvas 封装
封装一个矩形
- 矩形的 x、y坐标
- 矩形的宽高
- 矩形的边框的线条样式、线条宽度
- 矩形填充的样式
- 矩形的旋转角度
- 矩形的缩小放大
function ItcastRect( option ) {// 矩形构造函数
this._init(option);
}
ItcastRect.prototype = { // 矩形的原型对象
_init: function( option ) { // 初始化方法
option = option || {};
this.x = option.x === 0 ? 0 : option.x || 100;
this.y = option.y === 0 ? 0 : option.y || 100;
this.w = option.w || 100;
this.h = option.h || 100;
this.angle = option.angle === 0 ? 0 : option.angle || 0;
this.fillStyle = option.fillStyle || 'silver';
this.strokeStyle = option.strokeStyle || 'red';
this.strokeWidth = option.strokeWidth || 4;
this.scaleX = option.scaleX || 1;
this.scaleY = option.Y || 1;
},
render: function( ctx ) {// 把矩形渲染到canvas中
ctx.save();
ctx.translate( this.x, this.y );// 位移画布
ctx.rotate( this.angle * Math.PI / 180 );// 旋转角度
ctx.scale( this.scaleX, this.scaleY );// 缩放
ctx.fillStyle = this.fillStyle;
ctx.fillRect( 0, 0, this.w, this.h ); // 填充矩形
ctx.lineWidth = this.strokeWidth; // 线宽
ctx.strokeStyle = this.strokeStyle; // 填充样式
ctx.strokeRect( 0,0,this.w,this.h ); // 描边样式
ctx.restore();
},
constructor: ItcastRect
};