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

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

js通過canvas生成圖片縮略圖

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

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

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

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); //以長寬最大值作為最終生成圖片的依據 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/,圖片素材是拿的我們做的一個相框制作應用的截圖,有興趣的朋友可以聯系我哦,大家一起討論,一起玩。

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 夹江县| 青川县| 乐都县| 武山县| 乐亭县| 上饶县| 东丰县| 都兰县| 陆丰市| 仪陇县| 定兴县| 固始县| 晋中市| 台中县| 明水县| 增城市| 三台县| 汾阳市| 宁安市| 滦平县| 三亚市| 莱阳市| 兴安县| 湛江市| 越西县| 滁州市| 靖宇县| 延长县| 商水县| 东乡族自治县| 博兴县| 贡山| 临邑县| 饶平县| 恩平市| 永川市| 蒲城县| 桂平市| 彭泽县| 金昌市| 凤冈县|