這篇文章主要為大家詳細介紹了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="/static/imghwm/default1.png" data-src="" id=" class="lazy" id="thum" alt="HTML5和JS實作本機圖片裁切並上傳功能" > <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程式碼
#
var $ = require('jquery'); var ajax = require('./ajax.js'); var preview = require('./preview.js'); var shear = require('./shear.js'); /** * 自定义头像 * @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 = $('<p>你的浏览器不支持自定义头像,可更换高版本的浏览器自定义头像</p>'); $('body').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('#preview'); //确定 warp .find('#submit') .unbind('click') .on('click',me.__submit.bind(me)); }; /** * 提交 * @private */ CustomerImg.prototype.__submit = function () { var cvsMove,data,fd; cvsMove = this.previewBox.find('#cvsMove'); data = cvsMove[0].toDataURL('image/jpg',1); fd = { 'customerImg':data }; ajax.upload(fd); }; /** * 判断是否支持自定义头像 * @returns {boolean} * @private */ CustomerImg.prototype.__isSupport = function () { var canvas,context; canvas= document.createElement('canvas'); if(typeof FileReader === 'function'&& 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('jquery'); /** * 预览类 * @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 === 'function'){ this.callback = callback; } if(this.__isSupport()){ chooseFile = boxElem.find('input[type="file"]'); chooseFile .on('change',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 !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg'){ alert('文件格式不正确'); 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('#preview'); img = preView.find('#preImg'); me = this; if(img.length <= 0){ preView.append($('<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/009/39a0cc22f775cd7bb6607cb03ca538da-1.jpg?x-oss-process=image/resize,p_40" class="lazy" id="preImg" alt="HTML5和JS實作本機圖片裁切並上傳功能" >')); } img = preView.find('#preImg'); //确保图片加载完成后再执行回调 img.on('load',function () { if(me.callback){ me.callback(me.type); } }); img.attr('src',reader.result); }; /** * 是否支持预览 * @returns {boolean} * @private */ Preview.prototype.__isSupport = function () { return typeof FileReader === 'function'; }; var preview = new Preview(); module.exports = preview;shear.js
var $ = require('jquery'); //由于要使用jquery-ui,所以将$暴露到window上。 window.$ = $; require('./jquery-ui.min.js'); /** * 切割 * @constructor */ function Shear() { this.previewBox = null; this.cvsMove = null; this.maxW = 200; this.maxH = 200; this.thum = null; this.fileType = 'image/jpeg'; } /** * 入口 * @param previewBox 预览元素的父元素 * @param fileType 裁剪的图片的类型 如:'image/jpg' * @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('#thum'); this.cvsMove = this.previewBox.find('#cvsMove'); 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('#preImg'); preview = this.previewBox.find('#preview'); naturalH = preImg[0].naturalHeight; naturalW = preImg[0].naturalWidth; //将canvas显示出来 this.cvsMove.show(); //将canvas置于(0,0) this.cvsMove .css({ "left":'0', 'top':'0' }); 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('2d'); cxt.drawImage(myImg[0],sx,sy,sW,sH,dx,dy,dW,dH); thum = this.thum; //将canvas上的图案显示到右侧 thum .attr('src',this.cvsMove[0].toDataURL(me.fileType,1)) .width(this.maxW) .height(this.maxH) }; var shear = new Shear(); module.exports = shear;#ajax.js
var $ = require('jquery'); function Ajax() { } /** * 上传图片数据 */ Ajax.prototype.upload = function (data) { $.ajax({ type:'POST', data:data, dataType:'json', url:'/test/PHP/upload.php', success:function (result) { if(result.status){ location.reload(); }else{ alert(result.msg); } } }); }; var ajax = new Ajax(); module.exports = ajax;最後在另一個檔案中,呼叫customerImg物件的start方法
var $ = require('jquery'); var customerImg =require('./customerImg.js'); customerImg.start($('#warp'));webpack的設定檔如下:##
var webpack = require('webpack'); module.exports = { entry:{ 'customerImg':'./js/test.js', 'jQuery':['jquery'] }, output:{ filename:'[name].js', library:'jQuery', libraryTarget:'umd' }, plugins:[ new webpack.optimize.CommonsChunkPlugin({ name:'jQuery', filename:'jquery.js' }) ] };
效果:
4.php程式碼
if(!empty($_POST) && isset($_POST['customerImg'])){ $img = $_POST['customerImg']; $imgdata = explode(',', $img); $uniName = md5 ( uniqid ( microtime ( true ), true ) ); $a = file_put_contents('./../uploads/'.$uniName.'.jpg', base64_decode($imgdata[1])); }
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!
相關推薦:
使用HTML5實作網頁音樂播放器Express使用html範本的程式碼分析#
以上是HTML5和JS實作本機圖片裁切並上傳功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

H5代碼的最佳實踐包括:1.使用正確的DOCTYPE聲明和字符編碼;2.採用語義化標籤;3.減少HTTP請求;4.使用異步加載;5.優化圖像。這些實踐能提升網頁的效率、可維護性和用戶體驗。

Web标准和技术从HTML4、CSS2和简单的JavaScript演变至今,经历了显著的发展。1)HTML5引入了Canvas、WebStorage等API,增强了Web应用的复杂性和互动性。2)CSS3增加了动画和过渡功能,使页面效果更加丰富。3)JavaScript通过Node.js和ES6的现代化语法,如箭头函数和类,提升了开发效率和代码可读性,这些变化推动了Web应用的性能优化和最佳实践的发展。

H5不僅僅是HTML5的簡稱,它代表了一個更廣泛的現代網頁開發技術生態:1.H5包括HTML5、CSS3、JavaScript及相關API和技術;2.它提供更豐富、互動、流暢的用戶體驗,能在多設備上無縫運行;3.使用H5技術棧可以創建響應式網頁和復雜交互功能。

H5與HTML5指的是同一個東西,即HTML5。 HTML5是HTML的第五個版本,帶來了語義化標籤、多媒體支持、畫布與圖形、離線存儲與本地存儲等新功能,提升了網頁的表現力和交互性。

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5開發需要掌握的工具和框架包括Vue.js、React和Webpack。 1.Vue.js適用於構建用戶界面,支持組件化開發。 2.React通過虛擬DOM優化頁面渲染,適合複雜應用。 3.Webpack用於模塊打包,優化資源加載。

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5通過語義化元素和ARIA屬性提升網頁的可訪問性和SEO效果。 1.使用、、等元素組織內容結構,提高SEO。 2.ARIA屬性如aria-label增強可訪問性,輔助技術用戶可順利使用網頁。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver Mac版
視覺化網頁開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。