Languages
[Edit]
EN

JavaScript - resize image in Vanilla JS

1 points
Created by:
AnnLen
1858

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

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:

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.