Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - resize image in Vanilla JS

0 contributions
1 points

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>
  <img id="dst-image">

    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);
            } catch (e) {
                if (onError) {
                    onError('Image saving error.');
        image.onerror = function() {
            if (onError) {
                onError('Image loading error.');
      	image.src = imageUrl;

    // Usage example:

    var srcUrl = '';
    var newWidth = 200;
    var newHeight = 135;

    function onReady(dataUrl) {
    	var dstImage = document.querySelector('#dst-image');
    	dstImage.src = dataUrl;
    function onError(message) {
    resizeImage(srcUrl, newWidth, newHeight, onReady, onError);


Used resource:

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more