Last active
February 18, 2025 14:08
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
} |
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
It works? how to use it in an HTML page?