Skip to content

Instantly share code, notes, and snippets.

@stormbreakers
Created December 30, 2015 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stormbreakers/73fd8a0f9dc61bd717f1 to your computer and use it in GitHub Desktop.
Save stormbreakers/73fd8a0f9dc61bd717f1 to your computer and use it in GitHub Desktop.
var maxWidth = 304; // Max width for the image
var maxHeight = 338; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = img.width; // Current image width
var height = img.height; // Current image height
var image = document.getElementById('userImage');
image.style.width = width + 'px';
image.style.height = height + 'px';
if (width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
image.style.width = maxWidth + 'px'; // Set new width
image.style.height = (height * ratio) + 'px'; // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
if (height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
image.style.height = maxHeight + 'px'; // Set new height
image.style.width = (width * ratio) + 'px'; // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.height = height;
canvas.width = width;
ctx.drawImage(img, 0, 0, width, height);
alert(ori);
switch(6){
case 2:
// horizontal flip
ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180° rotate left
ctx.translate(canvas.width, canvas.height);
ctx.rotate(Math.PI);
break;
case 4:
// vertical flip
ctx.translate(0, canvas.height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
// 90° rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -canvas.height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(canvas.width, -canvas.height);
ctx.scale(-1, 1);
break;
case 8:
// 90° rotate left
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-canvas.width, 0);
break;
}
document.getElementById('userImage').src = canvas.toDataURL();
document.getElementById('loader').style.display = 'none';
};
img.src = URL.createObjectURL(event.target.files[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment