国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

js通過canvas生成圖片縮略圖

瀏覽:193日期:2024-04-17 18:19:49

現(xiàn)今大部分的網(wǎng)絡應用在上傳圖片的時候都會同時保存幾種尺寸的圖片,專業(yè)術語也就是生成縮略圖,而對于生成縮略圖一般做法是通過后端語言php等來生成,但是為了給服務器減壓,我們或許可以從前端來著手,先生成好不同尺寸的縮略圖,傳給后端,而后端只需要將前端傳過來的圖片進行存儲就好了。

使用Canvas我們可以輕松生成各種尺寸的圖片,具體實現(xiàn)如下:

function resizeImage(src,callback,w,h){ var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), im = new Image(); w = w || 0, h = h || 0; im.onload = function(){ //為傳入縮放尺寸用原尺寸 !w && (w = this.width); !h && (h = this.height); //以長寬最大值作為最終生成圖片的依據(jù) if(w !== this.width || h !== this.height){ var ratio; if(w>h){ ratio = this.width / w; h = this.height / ratio; }else if(w===h){ if(this.width>this.height){ ratio = this.width / w; h = this.height / ratio; }else{ ratio = this.height / h; w = this.width / ratio; } }else{ ratio = this.height / h; w = this.width / ratio; } } //以傳入的長寬作為最終生成圖片的尺寸 if(w>h){ var offset = (w - h) / 2; canvas.width = canvas.height = w; ctx.drawImage(im,0,offset,w,h); }else if(w<h){ var offset = (h - w) / 2; canvas.width = canvas.height = h; ctx.drawImage(im,offset,0,w,h); }else{ canvas.width = canvas.height = h; ctx.drawImage(im,0,0,w,h); } callback(canvas.toDataURL('image/png')); } im.src = src;}

在線實例地址:http://demo.jb51.net/js/2020/thumbnail/,圖片素材是拿的我們做的一個相框制作應用的截圖,有興趣的朋友可以聯(lián)系我哦,大家一起討論,一起玩。

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 自贡市| 师宗县| 阜阳市| 镇宁| 吐鲁番市| 崇州市| 昌乐县| 隆安县| 兴业县| 吴忠市| 武宣县| 棋牌| 南丰县| 精河县| 馆陶县| 太仓市| 绵阳市| 南漳县| 民丰县| 右玉县| 大田县| 驻马店市| 天气| 明星| 顺昌县| 冀州市| 古蔺县| 土默特右旗| 米林县| 交城县| 京山县| 九江市| 伊通| 剑阁县| 延津县| 乐清市| 金华市| 临朐县| 淮滨县| 新乡县| 大港区|