Coder Social home page Coder Social logo

image-show's Introduction

image-show

基于canvas实现图片上传/预览/裁剪的demo

上传图片后台测试时候基于nodejsexpress框架

启动步骤:

  1. 安装依赖
npm install
  1. 切换到dev目录下
node app.js

npm run dev

实现思路:

  1. 利用原生的input标签的file类型调用本地图片上传;

  2. 监听inputchange事件,能实时知道用户是否选中图片;

  3. 新建一个formData对象,以键值对的形式存放file对象,demo中以image作为键名;

  4. 新建一个fileReader对象,将读取到的file对象转成base64编码的形式;

  5. 监听fileReaderonload事件,同时新建一个image对象,在这个事件的回调函数中,将第四步中的编码后的图片地址作为图片引用路径;

  6. 监听创建的imageonload事件,利用canvasdrawImage方法,将图片内容以canvas的形式展示在浏览器上;

  7. 裁剪的思路 利用监听鼠标的mousedownmousemovemouseup事件,主要是在鼠标移动的事件中,一边清除画布内容的同时,利用canvasstrokeRect方法模拟做出一个矩形裁剪框,getImageData以及putImageData方法实时同步选中区域的x,y坐标以及选中区域宽高可以实现裁剪选区域与预览区域实时同步;

  8. 抬起鼠标完成预览图片绘制;

  9. 最终利用原生ajax实现form-data类型的上传;

image-show's People

Contributors

megan-ta avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.