基于canvas实现图片上传/预览/裁剪的demo
上传图片后台测试时候基于nodejs
的express
框架
启动步骤:
- 安装依赖
npm install
- 切换到
dev
目录下
node app.js
npm run dev
实现思路:
-
利用原生的
input
标签的file
类型调用本地图片上传; -
监听
input
的change
事件,能实时知道用户是否选中图片; -
新建一个
formData
对象,以键值对的形式存放file
对象,demo中以image
作为键名; -
新建一个
fileReader
对象,将读取到的file
对象转成base64
编码的形式; -
监听
fileReader
的onload
事件,同时新建一个image
对象,在这个事件的回调函数中,将第四步中的编码后的图片地址作为图片引用路径; -
监听创建的
image
的onload
事件,利用canvas
的drawImage
方法,将图片内容以canvas
的形式展示在浏览器上; -
裁剪的思路 利用监听鼠标的
mousedown
和mousemove
和mouseup
事件,主要是在鼠标移动的事件中,一边清除画布内容的同时,利用canvas
的strokeRect
方法模拟做出一个矩形裁剪框,getImageData
以及putImageData
方法实时同步选中区域的x,y坐标以及选中区域宽高可以实现裁剪选区域与预览区域实时同步; -
抬起鼠标完成预览图片绘制;
-
最终利用原生
ajax
实现form-data
类型的上传;