Languages
[Edit]
EN

JavaScript - resize image in Vanilla JS

4 points
Created by:
starcraf35
424

In this article, we would like to show how to resize or reduce image size in pure JavaScript using canvas.

Image resizing in Vanilla JS.
Image resizing in Vanilla JS.

Practical example:

// ONLINE-RUNNER:browser;

<!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>

Used resource:

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join