首页 web前端 H5教程 HTML5和JS实现本地图片裁剪并上传功能

HTML5和JS实现本地图片裁剪并上传功能

Jun 11, 2018 pm 05:34 PM

这篇文章主要为大家详细介绍了HTML5本地图片裁剪并上传的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近做了一个项目,这个项目中需要实现的一个功能是:用户自定义头像(用户在本地选择一张图片,在本地将图片裁剪成满足系统要求尺寸的大小)。这个功能的需求是:头像最初剪切为一个正方形。如果选择的图片小于规定的头像要求尺寸,那么这整张图片都会作为头像。如果大于规定的尺寸,那么用户可以选择要裁剪的区域。用户点击确定按钮,就将裁剪得到的图片数据发送到服务器,在后端将图片数据保存成一个文件。

要完成上述功能,涉及到的知识有:ajax,canvas和html5中的files接口。我将实现这个功能的代码封装到了4个模块中,分别是ajax.js,preview.js,shear.js和customerImg.js。

ajax.js:用于发送ajax请求。

preview.js:用于图片预览

shear.js:用于裁剪图片

customer.js:自定义头像。在这个模块中药引入ajax.js,preview.js和shear.js

我使用webpack进行打包。我还使用了jquery和jquery-ui。

我从这个项目中抽离出了这个功能。下面是这个功能的详细代码。

1.HTML代码

<p class="m-warp" id="warp">
  <p class="item">
   <input type="file" name="img" id="img" hidden>
   <label for="img">选择图片</label>
  </p>
  <p class="item clearfix">
   <p class="col col-1">
    <p class="preview" id="preview">
     <p class="mask"></p>
     <canvas class="cvsMove" id="cvsMove"></canvas>
    </p>
   </p>

   <p class="thum col-2 col">
    <p>预览</p>
    <img src="" id="thum">
    <p class="f-text-l f-marTop-20">
     <button class="shear" id="submit">确定</button>
    </p>
   </p>
  </p>
 </p>
登录后复制

2.CSS代码

.clearfix:after{
 content: "";
 display: block;
 clear: both;
 height: 0;
 overflow: hidden;
 visibility: hidden;
}
img{
  vertical-align: middle;
  max-width:100%
}
.m-warp{
 width: 800px;
}
.item{
 margin-top: 20px;
}
.col{
 float: left;
}
.col-1{
 position: relative;
 width: 450px;
 height: 450px;
 outline: 1px solid #333;
}
.preview{
 display: inline-block;
}
.col-2{
 width: 300px;
 margin-left: 50px;
}
label{
 display: block;
 text-align: center;
 width: 100px;
 font-size: 16px;
 color: #fff;
 background-color: #888888;
 height: 30px;
 line-height: 30px;
}
.mask{
 position: absolute;
 z-index: 1;
 top:0;
 left: 0;
 bottom: 0;
 right: 0;
 background-color: rgba(0,0,0,.4);
}
.cvsMove{
 position: absolute;
 z-index: 2;
 outline: 2px dotted #333;
 cursor: move;
 display: none;
}
登录后复制

有了css和html的运行结果如下:

3.js代码

customerImg.js

var $ = require(&#39;jquery&#39;);
var ajax = require(&#39;./ajax.js&#39;);
var preview = require(&#39;./preview.js&#39;);
var shear = require(&#39;./shear.js&#39;);
/**
 * 自定义头像
 * @constructor
 */
function CustomerImg() {
 this.isSupport = null;
 this.previewBox = null;
 this.warp = null;
}
/**
 * 入口
 * @param warp 操作区域 jquery节点
 */
CustomerImg.prototype.start = function (warp) {
 var info,me,warpBox;
 me = this;
 this.isSupport = this.__isSupport();
 if(!this.isSupport) {
  info = $(&#39;<p>你的浏览器不支持自定义头像,可更换高版本的浏览器自定义头像</p>&#39;);
  $(&#39;body&#39;).html(info);
  return this;
 }
 //判断操作区域示范存在
 if(warp && warp.length > 0){
  this.warp = warp;
 }else{
  return this;
 }
 //预览
 preview.start(warp,shear.start.bind(shear,warp));
 this.previewBox = warp.find(&#39;#preview&#39;);
 //确定
 warp
  .find(&#39;#submit&#39;)
  .unbind(&#39;click&#39;)
  .on(&#39;click&#39;,me.__submit.bind(me));
};
/**
 * 提交
 * @private
 */
CustomerImg.prototype.__submit = function () {
 var cvsMove,data,fd;
 cvsMove = this.previewBox.find(&#39;#cvsMove&#39;);
 data = cvsMove[0].toDataURL(&#39;image/jpg&#39;,1);
 fd = {
  &#39;customerImg&#39;:data
 };
 ajax.upload(fd);
};
/**
 * 判断是否支持自定义头像
 * @returns {boolean}
 * @private
 */
CustomerImg.prototype.__isSupport = function () {
 var canvas,context;
 canvas= document.createElement(&#39;canvas&#39;);
 if(typeof FileReader === &#39;function&#39;&& canvas.getContext && canvas.toDataURL){
  return true;
 }else{
  return false;
 }
};
var customerImg = new CustomerImg();
module.exports = customerImg;
登录后复制

preview.js

/**
 * Created by star on 2017/3/7.
 */
var $ = require(&#39;jquery&#39;);
/**
 * 预览类
 * @constructor
 */
function Preview() {
 this.boxElem = null;
 this.callback = null;
 this.type = null;
}
/**
 * 入口
 * @param boxElem 操作区域
 * @param callback 预览结束的回调函数
 */
Preview.prototype.start = function (boxElem,callback) {
 var chooseFile,me;
 me = this;
 if(! boxElem || boxElem.length <= 0) return this;
 this.boxElem = boxElem;
 if(typeof callback === &#39;function&#39;){
  this.callback = callback;
 }
 if(this.__isSupport()){
  chooseFile = boxElem.find(&#39;input[type="file"]&#39;);
  chooseFile
   .on(&#39;change&#39;,me.fileChange.bind(me))
 }
};
/**
 * 选择图片的事件处理程序
 * @param event
 */
Preview.prototype.fileChange = function (event) {
 var target,reader,file,me,type;
 target = event.target;
 me = this;
 file = target.files[0];
 type = file.type;
 this.type = type;
 if(type !== &#39;image/png&#39; && type !== &#39;image/jpg&#39; && type !== &#39;image/jpeg&#39;){
  alert(&#39;文件格式不正确&#39;);
  return this;
 }
 reader = new FileReader();
 if(file){
  reader.readAsDataURL(file);
 }
 reader.onload = function () {
  me.show(reader);
 }
};
/**
 * 显示从本地选择的图片
 * @param reader fileReader对象
 */
Preview.prototype.show = function (reader) {
 var preView,img,me;
 preView = this.boxElem.find(&#39;#preview&#39;);
 img = preView.find(&#39;#preImg&#39;);
 me = this;
 if(img.length <= 0){
  preView.append($(&#39;<img id="preImg">&#39;));
 }
 img = preView.find(&#39;#preImg&#39;);
 //确保图片加载完成后再执行回调
 img.on(&#39;load&#39;,function () {
  if(me.callback){
   me.callback(me.type);
  }
 });
 img.attr(&#39;src&#39;,reader.result);
};
/**
 * 是否支持预览
 * @returns {boolean}
 * @private
 */
Preview.prototype.__isSupport = function () {
 return typeof FileReader === &#39;function&#39;;
};
var preview = new Preview();
module.exports = preview;
登录后复制

shear.js

var $ = require(&#39;jquery&#39;);
//由于要使用jquery-ui,所以将$暴露到window上。
window.$ = $;
require(&#39;./jquery-ui.min.js&#39;);
/**
 * 切割
 * @constructor
 */
function Shear() {
 this.previewBox = null;
 this.cvsMove = null;
 this.maxW = 200;
 this.maxH = 200;
 this.thum = null;
 this.fileType = &#39;image/jpeg&#39;;
}
/**
 * 入口
 * @param previewBox 预览元素的父元素
 * @param fileType 裁剪的图片的类型 如:&#39;image/jpg&#39;
 * @returns {Shear}
 */
Shear.prototype.start = function (previewBox,fileType) {
 if(!arguments.length) return this;
 var me = this;
 this.previewBox = previewBox;
 if(fileType){
  this.fileType = fileType;
 }
 this.thum = this.previewBox.find(&#39;#thum&#39;);
 this.cvsMove = this.previewBox.find(&#39;#cvsMove&#39;);
 this.showCanvas();
 return this;

};
/**
 * 显示出canvas
 */
Shear.prototype.showCanvas = function () {
 var preImg,h,w,me,cvsH,cvsW,rateH,rateW,naturalH,naturalW,preview;
 me = this;
 preImg = this.previewBox.find(&#39;#preImg&#39;);
 preview = this.previewBox.find(&#39;#preview&#39;);
 naturalH = preImg[0].naturalHeight;
 naturalW = preImg[0].naturalWidth;
 //将canvas显示出来
 this.cvsMove.show();
 //将canvas置于(0,0)
 this.cvsMove
  .css({
   "left":&#39;0&#39;,
   &#39;top&#39;:&#39;0&#39;
  });
 h = preImg.height();
 w = preImg.width();
 //规定裁剪出的图片尺寸为200px*200px
 //要保证裁剪的图片不变形
 if(h < this.maxH || w < this.maxW){
  this.cvsMove[0].width = cvsW = Math.min(h,w);
  this.cvsMove[0].height = cvsH = Math.min(h,w);
 }else{
  this.cvsMove[0].width= cvsW = this.maxW;
  this.cvsMove[0].height= cvsH = this.maxH;
 }
 rateH = h/naturalH;
 rateW = w/naturalW;
 this.__drawImg(preImg,0,0,cvsW/rateW,cvsH/rateH,0,0,cvsW,cvsH);
 //使用jquery-ui中的功能使canvas可以移动
 this.cvsMove.draggable(
  {
   containment: "parent",
   drag:function (event,ui) {
    var left,top;
    left = ui.position.left;
    top = ui.position.top;
    //canvas每次移动都有从新绘制图案
    me.__drawImg(preImg,left/rateW,top/rateH,cvsW/rateW,cvsH/rateH,0,0,cvsW,cvsH);
   }
  }
 )
};
/**
 * 在canvas上显示图片
 * @param myImg 要显示的图片节点
 * @param sx 图片的起点在原图片上的x坐标
 * @param sy 图片的起点在原图上的y坐标
 * @param sW 在原图上的宽度
 * @param sH 在原图上的高度
 * @param dx 起点在canvas上的x坐标
 * @param dy 起点在canvas上的y坐标
 * @param dW 在canvas上的宽度
 * @param dH 在canvas上的高度
 * @private
 */
Shear.prototype.__drawImg = function (myImg,sx,sy,sW,sH,dx,dy,dW,dH) {
 var cxt,thum,me;
 me = this;
 cxt = this.cvsMove[0].getContext(&#39;2d&#39;);
 cxt.drawImage(myImg[0],sx,sy,sW,sH,dx,dy,dW,dH);
 thum = this.thum;
 //将canvas上的图案显示到右侧
 thum
  .attr(&#39;src&#39;,this.cvsMove[0].toDataURL(me.fileType,1))
  .width(this.maxW)
  .height(this.maxH)
};
var shear = new Shear();
module.exports = shear;
登录后复制

ajax.js

var $ = require(&#39;jquery&#39;);
function Ajax() {

}
/**
 * 上传图片数据
 */
Ajax.prototype.upload = function (data) {
 $.ajax({
  type:&#39;POST&#39;,
  data:data,
  dataType:&#39;json&#39;,
  url:&#39;/test/PHP/upload.php&#39;,
  success:function (result) {
   if(result.status){
    location.reload();
   }else{
    alert(result.msg);
   }
  }
 });
};
var ajax = new Ajax();
module.exports = ajax;
登录后复制

最后在另一个文件中,调用customerImg对象的start方法

var $ = require(&#39;jquery&#39;);
var customerImg =require(&#39;./customerImg.js&#39;);
customerImg.start($(&#39;#warp&#39;));
登录后复制

webpack的配置文件如下:

var webpack = require(&#39;webpack&#39;);
module.exports = {
 entry:{
  &#39;customerImg&#39;:&#39;./js/test.js&#39;,
  &#39;jQuery&#39;:[&#39;jquery&#39;]
 },
 output:{
  filename:&#39;[name].js&#39;,
  library:&#39;jQuery&#39;,
  libraryTarget:&#39;umd&#39;
 },
 plugins:[
  new webpack.optimize.CommonsChunkPlugin({
   name:&#39;jQuery&#39;,
   filename:&#39;jquery.js&#39;
  })
 ]
};
登录后复制

效果:

4.php代码

if(!empty($_POST) && isset($_POST[&#39;customerImg&#39;])){
 $img = $_POST[&#39;customerImg&#39;];
 $imgdata = explode(&#39;,&#39;, $img);
 $uniName = md5 ( uniqid ( microtime ( true ), true ) );
 $a = file_put_contents(&#39;./../uploads/&#39;.$uniName.&#39;.jpg&#39;, base64_decode($imgdata[1]));
}
登录后复制

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

使用HTML5实现网页音乐播放器

Express使用html模板的代码分析

以上是HTML5和JS实现本地图片裁剪并上传功能的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

h5项目怎么运行 h5项目怎么运行 Apr 06, 2025 pm 12:21 PM

运行 H5 项目需要以下步骤:安装 Web 服务器、Node.js、开发工具等必要工具。搭建开发环境,创建项目文件夹、初始化项目、编写代码。启动开发服务器,使用命令行运行命令。在浏览器中预览项目,输入开发服务器 URL。发布项目,优化代码、部署项目、设置 Web 服务器配置。

H5页面制作究竟指什么 H5页面制作究竟指什么 Apr 06, 2025 am 07:18 AM

H5 页面制作是指使用 HTML5、CSS3 和 JavaScript 等技术,创建跨平台兼容的网页。其核心在于浏览器解析代码,渲染结构、样式和交互功能。常见技术包括动画效果、响应式设计和数据交互。为避免错误,应使用开发者工具调试;而性能优化和最佳实践则包括图像格式优化、减少请求和代码规范等,以提高加载速度和代码质量。

如何使用地理位置API处理用户位置隐私和权限? 如何使用地理位置API处理用户位置隐私和权限? Mar 18, 2025 pm 02:16 PM

本文讨论了使用GeOlocation API管理用户位置隐私和权限,并强调要求权限,确保数据安全性并遵守隐私法律的最佳实践。

如何将HTML5拖放API用于交互式用户界面? 如何将HTML5拖放API用于交互式用户界面? Mar 18, 2025 pm 02:17 PM

本文介绍了如何使用HTML5拖放API来创建交互式用户界面,详细介绍了使元素可拖动的步骤,处理关键事件并通过自定义反馈来增强用户体验。它还讨论了一个常见的陷阱

h5怎么制作点击图标 h5怎么制作点击图标 Apr 06, 2025 pm 12:15 PM

制作 H5 点击图标的步骤包括:在图像编辑软件中准备方形源图像。在 H5 编辑器中添加交互性,设置点击事件。创建覆盖整个图标的热点。设置点击事件的操作,如跳转页面或触发动画。导出 H5 文档为 HTML、CSS 和 JavaScript 文件。将导出的文件部署到网站或其他平台。

H5页面制作是否需要持续维护 H5页面制作是否需要持续维护 Apr 05, 2025 pm 11:27 PM

H5页面需要持续维护,这是因为代码漏洞、浏览器兼容性、性能优化、安全更新和用户体验提升等因素。有效维护的方法包括建立完善的测试体系、使用版本控制工具、定期监控页面性能、收集用户反馈和制定维护计划。

H5页面制作适合哪些应用场景 H5页面制作适合哪些应用场景 Apr 05, 2025 pm 11:36 PM

H5(HTML5)适合应用于轻量级应用,如营销活动页面、产品展示页面和企业宣传微网站。它优势在于跨平台性和丰富的交互性,但局限性在于复杂的交互和动画、本地资源访问和离线功能。

html下一页功能 html下一页功能 Apr 06, 2025 am 11:45 AM

<p>可以通过 HTML 创建下一页功能,步骤包括:创建容器元素、分割内容、添加导航链接、隐藏其他页面、添加脚本。该功能允许用户浏览分段的内容,每次只显示一页,适用于展示大量数据或内容。</p>

See all articles