Created
April 23, 2017 07:31
-
-
Save Bloodb0ne/39b99870804e6d79e09b992566702102 to your computer and use it in GitHub Desktop.
A scaling function to fit images into a predefined canvas with callback
This file contains 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
function drawImageScaled(src,w,h,callback) { | |
var img = $('<img>').attr('src',src); | |
img.on('load',function(){ | |
var image = img[0]; | |
var canvas = $('<canvas>').attr('width',w).attr('height',h)[0]; | |
var ctx = canvas.getContext("2d"); | |
// var canvas = ctx.canvas ; | |
var hR = canvas.width / image.width ; | |
var vR = canvas.height / image.height ; | |
var ratio = Math.min ( hR, vR ); | |
var offset_x = ( canvas.width - image.width*ratio ) / 2; | |
var offset_y = ( canvas.height - image.height*ratio ) / 2; | |
ctx.clearRect(0,0,canvas.width, canvas.height); | |
ctx.drawImage(image, 0,0, image.width, image.height, | |
offset_x,offset_y,image.width*ratio, image.height*ratio); | |
callback(canvas.toDataURL("image/png")); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment