Here is the outline of your resize function:
- create a new canvas with
document.createElement("canvas")
and a context for the canvas. - create a new Image object and set its .src
- create a .onload for the new image that draws the resized image to the canvas using drawImage.
- return the new canvas element
Example code and a Demo: http://jsfiddle.net/m1erickson/UTjW8/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var imageSource="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/faces.png";
var canvas=resize(imageSource,125,125);
document.body.appendChild(canvas);
// scale an image to canvas maintaining an aspect ratio
function resize(srcURL,maxWidth,maxHeight){
var tcanvas=document.createElement("canvas");
var tctx=tcanvas.getContext("2d");
var img=new Image();
img.onload=function(){
var iw=img.width;
var ih=img.height;
var ratio = Math.min(maxWidth/iw,maxHeight/ih);
tcanvas.width=iw*ratio;
tcanvas.height=ih*ratio;
tctx.drawImage(img,0,0,iw,ih,0,0,iw*ratio,ih*ratio);
}
img.src=srcURL;
return(tcanvas);
}
}); // end $(function(){});
</script>
</head>
<body>
</body>
</html>