>  기사  >  웹 프론트엔드  >  HTML5 및 JS는 로컬 이미지 자르기 및 업로드 기능을 구현합니다.

HTML5 및 JS는 로컬 이미지 자르기 및 업로드 기능을 구현합니다.

不言
不言원래의
2018-06-11 17:34:026566검색

이 글은 주로 HTML5 로컬 이미지 크롭 및 업로드 관련 정보를 자세하게 소개하고 있습니다. 관심 있는 친구들이 참고하면 좋을 것 같습니다.

제가 최근에 진행한 프로젝트 중 하나입니다. 이 프로젝트의 기능은 다음과 같습니다. 사용자 정의 아바타(사용자가 로컬에서 사진을 선택하고 시스템 요구 사항을 충족하는 크기로 로컬에서 사진을 자릅니다). 이 기능에 대한 요구 사항은 다음과 같습니다. 아바타는 처음에 정사각형으로 잘립니다. 선택한 이미지가 필요한 아바타 크기보다 작은 경우 전체 이미지가 아바타로 사용됩니다. 지정된 크기보다 큰 경우 사용자는 잘라낼 영역을 선택할 수 있습니다. 사용자가 확인 버튼을 클릭하면 크롭된 이미지 데이터가 서버로 전송되고, 이미지 데이터는 백엔드에 파일로 저장됩니다.

위 기능을 완료하려면 ajax, 캔버스 및 html5의 파일 인터페이스와 관련된 지식이 필요합니다. 이 기능을 구현하기 위한 코드를 ajax.js, Preview.js, shear.js 및 customerImg.js라는 4개의 모듈로 캡슐화했습니다.

ajax.js: Ajax 요청을 보내는 데 사용됩니다.

preview.js: 이미지 미리보기용

shear.js: 이미지 자르기용

customer.js: 사용자 정의 아바타. 이번 모듈에서는 ajax.js, Preview.js, shear.js를 소개하며 패키징을 위해 webpack을 사용합니다. 나는 또한 jquery와 jquery-ui를 사용했습니다.

이 프로젝트에서 이 기능을 추출했습니다. 아래는 이 함수에 대한 자세한 코드입니다.

1.HTML code


<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 code


.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. Node.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 객체의 시작 메소드를 호출합니다

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 code


rrre 에에

위 내용은 이 글의 내용입니다. 모든 내용이 여러분의 학습에 도움이 되었으면 좋겠습니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요!

관련 권장사항:

HTML5를 사용하여 웹 뮤직 플레이어 구현


html 템플릿을 사용하여 코드 분석 표현


위 내용은 HTML5 및 JS는 로컬 이미지 자르기 및 업로드 기능을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.