Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Last active September 17, 2019 12:07
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save MikeRogers0/6264546 to your computer and use it in GitHub Desktop.
Save MikeRogers0/6264546 to your computer and use it in GitHub Desktop.
An example of how to resize an image on the fly with javascript.
// The function that scales an images with canvas then runs a callback.
function scaleImage(url, width, height, liElm, callback){
var img = new Image(),
width = width,
height = height,
callback;
// When the images is loaded, resize it in canvas.
img.onload = function(){
var canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height= height;
// draw the img into canvas
ctx.drawImage(this, 0, 0, width, height);
// Run the callback on what to do with the canvas element.
callback(canvas, liElm);
};
img.src = url;
}
// List of imgur images
var images = ['u0s09PV','bdRlP3o','o7lwgZo','wvOjdUJ','D0lsDQz','sB46sHZ','nvRcyJM'],
imagesList = document.getElementById('imagesList');
// Loop through the images.
for(i in images){
// make an li we can use in the callback.
liElm = document.createElement('li');
// append the currently empty li into the ul.
imagesList.appendChild(liElm);
scaleImage('http://i.imgur.com/'+images[i]+'.jpg', 150, 150, liElm, function(canvas, liElm){
// Append the canvas element to the li.
liElm.appendChild(canvas);
});
}
@agaezcode
Copy link

It works? how to use it in an HTML page?

@daslicht
Copy link

proportional resizing would be a nice addition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment