JS圖片上傳壓縮和this指向問題

HTML:

<input type="file" name="image" accept="image/*"@change='onUpload'></input>

JS:

toDataURL(file, c, isBase) {

? ? ? ? var reader = new FileReader();

? ? ? ? reader.onload = function () {

? ? ? ? ? ? c(this.result)

? ? ? ? }

? ? ? ? reader.readAsDataURL(file);

? ? },

? ? dealImage:function(path, obj, callback) {

? ? window.pmb=this;

? ? ? ? var img = new Image();

? ? ? ? img.src = path;

? ? ? ? img.onload = function () {

? ? ? ? ? ? var that = this;

? ? ? ? ? ? // 默認(rèn)按比例壓縮

? ? ? ? ? ? var w = that.width,

? ? ? ? ? ? ? ? h = that.height,

? ? ? ? ? ? ? ? scale = w / h;

? ? ? ? ? ? w = obj.width || w;

? ? ? ? ? ? h = obj.height || (w / scale);

? ? ? ? ? ? //生成canvas

? ? ? ? ? ? var canvas = document.createElement('canvas');

? ? ? ? ? ? var ctx = canvas.getContext('2d');

? ? ? ? ? ? // 創(chuàng)建屬性節(jié)點

? ? ? ? ? ? var anw = document.createAttribute("width");

? ? ? ? ? ? anw.nodeValue = w;

? ? ? ? ? ? var anh = document.createAttribute("height");

? ? ? ? ? ? anh.nodeValue = h;

? ? ? ? ? ? canvas.setAttributeNode(anw);

? ? ? ? ? ? canvas.setAttributeNode(anh);

? ? ? ? ? ? ctx.drawImage(that, 0, 0, w, h);

? ? ? ? ? ? canvas.toBlob(function (callback) {

? ? ? ? ? ? console.log("callback",callback);

? ? ? ? ? ? ? ? let formData = new FormData();

? ? ? ? ? ? ? ? formData.append("file", callback);

? ? ? ? ? ? ? ? window.pmb.axios

? ? ? ? ? ? ? ? ? .post(URL, formData, {

? ? ? ? ? ? ? ? ? ? headers: { "Content-Type": "multipart/form-data" }

? ? ? ? ? ? ? ? ? })

? ? ? ? ? ? ? ? ? .then(res => {

? ? ? ? ? ? ? ? ? });?

? ? ? ? ? ? })

? ? ? ? }

? ? },

? ? onUpload(e) {

? ? ? let self=this;

? ? ? self.toDataURL(this.$refs.input.files[0],function(base){

? ? ? ? ? ? self.dealImage(base, {width:400,height:400}, function(blob){

? ? ? ? ? ? ? ? window.open(URL.createObjectURL(blob));


? ? ? ? ? ? });

? ? ? });

? ? },

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容