js resize image in vanilla js
HTML[Edit]
+
0
-
0
js resize image in Vanilla JS
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 47 48 49 50 51 52 53<!doctype html> <html> <body> <img id="dst-image"> <script> function resizeImage(imageUrl, newWidth, newHeight, onReady, onError) { var image = document.createElement('img'); image.onload = function() { var canvas = document.createElement('canvas'); canvas.width = newWidth; canvas.height = newHeight; var context = canvas.getContext('2d'); context.drawImage(image, 0, 0, newWidth, newHeight); try { // quality=0.9 (from 0 to 1.0) var dataUrl = canvas.toDataURL('image/jpeg', 0.9); onReady(dataUrl); } catch (e) { if (onError) { onError('Image saving error.'); } } }; image.onerror = function() { if (onError) { onError('Image loading error.'); } }; image.src = imageUrl; }; // Usage example: var srcUrl = 'https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png'; var newWidth = 200; var newHeight = 135; function onReady(dataUrl) { var dstImage = document.querySelector('#dst-image'); dstImage.src = dataUrl; } function onError(message) { console.error(message); } resizeImage(srcUrl, newWidth, newHeight, onReady, onError); </script> </body> </html>