一、概念
离屏canvas是在内存中创建一个canvas元素,未通过dom操作显示到页面上去
二、场景
- 用于需频繁调用canvas API
- 底部背景(canvas绘制的)不需要改变的
- 批量上传图片,web端压缩
- web绘制图片,本地保存
三、用法
- 创建一个canvas元素
- web绘制所需图形
- 通过canvas API drawImage方法绘制到页面canvas上去显示
四、代码展示
function animate(y, isDown){ ctx.clearRect(0, 0, 200, 200) var canvas = document.createElement('canvas') canvas.width = 200 canvas.height = 200 var ctx1 = canvas.getContext('2d') ctx1.arc(40, 40, 40, 0, 2 * Math.PI) ctx1.clip() ctx1.filStyle = 'rgba(0, 255, 255, .2)' ctx1.fillRect(0, 0, 80, 80) ctx1.clearRect(0, 0, 80, y)
ctx1.beginPath() ctx1.strokeStyle = 'rgba(0, 255, 255, 1)' ctx1.moveTo(0, y) ctx1.lineTo(80, y) ctx1.closePath() ctx1.stroke()
ctx.drawImage(canvas, 0, 0) }
五、优点
- 提供性能(离屏canvas的操作都是在内存中进行并且离屏canvas的任何操作都不会导致页面变(重绘、重排))
- 减少冗余操作