現(xiàn)今大部分的網(wǎng)絡(luò)應用在上傳圖片的時候都會同時保存幾種尺寸的圖片,專業(yè)術(shù)語也就是生成縮略圖,而對于生成縮略圖一般做法是通過后端語言php等來生成,但是為了給服務器減壓,我們或許可以從前端來著手,先生成好不同尺寸的縮略圖,傳給后端,而后端只需要將前端傳過來的圖片進行存儲就好了。
使用Canvas我們可以輕松生成各種尺寸的圖片,具體實現(xiàn)如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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; } |
圖片素材是拿的我們做的一個相框制作應用的截圖,有興趣的朋友可以聯(lián)系我哦,大家一起討論,一起玩。
原文鏈接:https://www.deanhan.cn/sh-html.html