code: function renderImageToCanvas(img, canvas, options) {
  		var iw = img.naturalWidth, ih = img.naturalHeight;
  		var width = options.width, height = options.height;
  		var x = options.x || 0, y = options.y || 0;
  		var ctx = canvas.getContext('2d');
  		if (detectSubsampling(img)) {
  			iw /= 2;
  			ih /= 2;
  		}
  		var d = 1024; // size of tiling canvas
  		var tmpCanvas = document.createElement('canvas');
  		tmpCanvas.width = tmpCanvas.height = d;
  		var tmpCtx = tmpCanvas.getContext('2d');
  		var vertSquashRatio = detectVerticalSquash(img, iw, ih);
  		var sy = 0;
  		while (sy < ih) {
  			var sh = sy + d > ih ? ih - sy : d;
  			var sx = 0;
  			while (sx < iw) {
  				var sw = sx + d > iw ? iw - sx : d;
  				tmpCtx.clearRect(0, 0, d, d);
  				tmpCtx.drawImage(img, -sx, -sy);
  				var dx = (sx * width / iw + x) << 0;
  				var dw = Math.ceil(sw * width / iw);
  				var dy = (sy * height / ih / vertSquashRatio + y) << 0;
  				var dh = Math.ceil(sh * height / ih / vertSquashRatio);
  				ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh);
  				sx += d;
  			}
  			sy += d;
  		}
  		tmpCanvas = tmpCtx = null;
  	}
docs: Rendering image element (with resizing) into the canvas element