Resize image in html5 canvas - javascript

I'm taking image input from user, then resizing and showing it on a canvas. Here is the code-
HTML-
<form class="cmxform">
<input type='file' id="Photo" />
<canvas id="canvas" width="300" height="200"></canvas>
</form>
JavaScript-
$("#Photo").change(function (e) {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function () {
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
}
});
But here I'm loosing the aspect ratio. Is there any way to do it?
UPDATE-
I've got the answer from this sa question -

Here is a snippet to help you for that
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
var fill = true;
if (fill)
{
$('#fill').attr("disabled", true);
}
$("#Photo").change(function (e) {
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function () {
if (fill)
{
drowImageFill(img);
}
else
{
drowImageCenter(img);
}
}
});
$("#fill").click(function(){
//console.log("fill");
var input = document.getElementById('Photo');
if (input.files[0] !== undefined)
{
img.src = URL.createObjectURL(input.files[0]);
img.onload = function () {
drowImageFill(img);
}
}
$('#fill').attr("disabled", true);
$('#center').attr("disabled", false);
fill = true;
});
$("#center").click(function(){
//console.log("center");
var input = document.getElementById('Photo');
if (input.files[0] !== undefined)
{
img.src = URL.createObjectURL(input.files[0]);
img.onload = function () {
drowImageCenter(img);
}
}
$('#center').attr("disabled", true);
$('#fill').attr("disabled", false);
fill = false;
});
//ratio formula
//http://andrew.hedges.name/experiments/aspect_ratio/
function drowImageFill(img){
ctx.clearRect(0, 0, canvas.width, canvas.height);
//detect closet value to canvas edges
if( img.height / img.width * canvas.width > canvas.height)
{
// fill based on less image section loss if width matched
var width = canvas.width;
var height = img.height / img.width * width;
offset = (height - canvas.height) / 2;
ctx.drawImage(img, 0, -offset, width, height);
}
else
{
// fill based on less image section loss if height matched
var height = canvas.height;
var width = img.width / img.height * height;
offset = (width - canvas.width) / 2;
ctx.drawImage(img, -offset , 0, width, height);
}
}
function drowImageCenter(img)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
if( img.height / img.width * canvas.width < canvas.height)
{
// center based on width
var width = canvas.width;
var height = img.height / img.width * width;
offset = (canvas.height - height) / 2;
ctx.drawImage(img, 0, offset, width, height);
}
else
{
// center based on height
var height = canvas.height;
var width = img.width / img.height * height;
offset = (canvas.width - width) / 2;
ctx.drawImage(img, offset , 0, width, height);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200" style="border:2px solid #000000;"></canvas>
<form class="cmxform">
<input type='file' id="Photo" />
</form>
<button id="fill">Fill</button>
<button id="center">Center</button>

Related

Reduce the dimension of base64 image maintaining aspect ratio in javascript

I have a base64 string for an image, which i have to display as an icon. If the dimension of an image are bigger i have to display icon maintaining aspect ratio.
I have written a logic to identify if the image is landscape or portrait based on which height and width will be settled for canvas. But seems height and width of icons are not proper as i have hard coded it.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var height, width;
if (this.height>this.width) {
height = 50;
width = 30;
} else if (this.height<this.width) {
height = 30;
width = 50;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(image,
0, 0, this.width, this.height,
0, 0, canvas.width, canvas.height
);
var scaledImage = new Image();
scaledImage.src = canvas.toDataURL();
Is there any way we can calculate it dynamically or any other way to preserve aspect ratio for icons.
Working Example can be found on https://codepen.io/imjaydeep/pen/ewBZRK
It will be fine if some space will be left on x-y axis.
You just need to calculate the scale or ratio and multiply both dimensions by that. Here's an example function, and here's your edited codepen.
Creates trimmed, scaled image:
function scaleDataURL(dataURL, maxWidth, maxHeight){
return new Promise(done=>{
var img = new Image;
img.onload = ()=>{
var scale, newWidth, newHeight, canvas, ctx;
if(img.width < maxWidth){
scale = maxWidth / img.width;
}else{
scale = maxHeight / img.height;
}
newWidth = img.width * scale;
newHeight = img.height * scale;
canvas = document.createElement('canvas');
canvas.height = newHeight;
canvas.width = newWidth;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight);
done(canvas.toDataURL());
};
img.src = dataURL;
});
}
Or, if you want the image to always be the provided dimensions with empty surrounding area, you can use this: (codepen)
Creates scaled image of exact provided dimensions:
function scaleDataURL(dataURL, maxWidth, maxHeight){
return new Promise(done=>{
var img = new Image;
img.onload = ()=>{
var scale, newWidth, newHeight, canvas, ctx, dx, dy;
if(img.width < maxWidth){
scale = maxWidth / img.width;
}else{
scale = maxHeight / img.height;
}
newWidth = img.width * scale;
newHeight = img.height * scale;
canvas = document.createElement('canvas');
canvas.height = maxWidth;
canvas.width = maxHeight;
ctx = canvas.getContext('2d');
dx = (maxWidth - newWidth) / 2;
dy = (maxHeight - newHeight) / 2;
console.log(dx, dy);
ctx.drawImage(img, 0, 0, img.width, img.height, dx, dy, newWidth, newHeight);
done(canvas.toDataURL());
};
img.src = dataURL;
});
}
For someone who search for a solution when the image is bigger that you need.
function scaleDataURL(dataURL: string, maxWidth: number, maxHeight: number) {
return new Promise((done) => {
var img = new Image()
img.onload = () => {
var scale, newWidth, newHeight, canvas, ctx
if (img.width > maxWidth) {
scale = maxWidth / img.width
} else if (img.height > maxHeight) {
scale = maxHeight / img.height
} else {
scale = 1
}
newWidth = img.width * scale
newHeight = img.height * scale
canvas = document.createElement('canvas')
canvas.height = newHeight
canvas.width = newWidth
ctx = canvas.getContext('2d')
console.log('img', 'scale', scale, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight)
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight)
done(canvas.toDataURL())
}
img.src = dataURL
})
}
Usage:
scaleDataURL(base64data, 600, 200)
.then((newBase64data) => {
console.log(newBase64data)
})
.catch((err) => console.log(err))

Rotating dynamic canvas image with javascript

I have the following code that allows the user to upload an image which gets put into a canvas, but once it has been drawn I want users to be able to rotate the image with the click of a button, but I don't know how to re-access the image object to be able to rotate the canvas. The code below is what works:
onFilePicked (e) {
const files = e.target.files;
for (let file of files) {
if(file !== undefined) {
let image = {
thumbnail: '/img/spinner.gif'
};
this.images.push(image);
this.loadImage(file, image);
}
}
},
loadImage(file, image) {
const fr = new FileReader();
fr.readAsDataURL(file);
fr.addEventListener('load', () => {
var img = new Image();
img.src = fr.result;
img.onload = () => {
image.thumbnail = this.resizeImage(img, 400, 300);
image.large = this.resizeImage(img, 1280, 960);
}
})
},
resizeImage(origImg, maxWidth, maxHeight) {
let scale = 1;
if (origImg.width > maxWidth) {
scale = maxWidth / origImg.width;
}
if (origImg.height > maxHeight) {
let scale2 = maxHeight / origImg.height;
if (scale2 < scale) scale = scale2;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = origImg.width * scale;
canvas.height= origImg.height * scale;
ctx.drawImage(origImg, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg");
},
And seen below is the function I built out to rotate the image- it works in that if I replace the code inside of the resizeImage function with the code below that the image is drawn in a way that is rotated correctly, but I don't know how to access the origImg object to be able to redraw the canvas in a separate function.
rotateImage(origImg, maxWidth, maxHeight){
let scale = 1;
if (origImg.width > maxWidth) {
scale = maxWidth / origImg.width;
}
if (origImg.height > maxHeight) {
let scale2 = maxHeight / origImg.height;
if (scale2 < scale) scale = scale2;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = origImg.height * scale;
canvas.height= origImg.width * scale;
ctx.translate(canvas.width, 0);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(origImg, 0, 0, canvas.height, canvas.width);
return canvas.toDataURL("image/jpeg");
},
Running this function as-is triggers the following console error:
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
How do I get/reuse the origImg object from the resizeImage function so I can use it in the rotateImage function?
you can try with this code:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(origImg,0,0); // Or at whatever offset you like
};
And apply your code insede onload function of img and finally transform img source to date URL
Try this code, based on one file picker, two buttons. The first one resize image and the second one rotete the image
function resizeImg()
{
var oPicker = document.getElementById('avatar');
var oImage = document.getElementById('imgOut');
var file = oPicker.files[0];
const fr = new FileReader();
fr.readAsDataURL(file);
fr.addEventListener('load', () => {
var img = new Image();
img.src = fr.result;
img.onload = () => {
oImage.thumbnail = this.resizeImage(img, 400, 300);
oImage.src = this.resizeImage(img, 1280, 960);
}
})
}
function rotateImg()
{
var imgOut = document.getElementById('imgOut');
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let scale = 1;
canvas.width = imgOut.height * scale;
canvas.height= imgOut.width * scale;
ctx.translate(canvas.width, 0);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(imgOut, 0, 0, canvas.height, canvas.width);
imgOut.src = canvas.toDataURL("image/jpeg");
}
function resizeImage(origImg, maxWidth, maxHeight) {
let scale = 1;
if (origImg.width > maxWidth) {
scale = maxWidth / origImg.width;
}
if (origImg.height > maxHeight) {
let scale2 = maxHeight / origImg.height;
if (scale2 < scale) scale = scale2;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = origImg.width * scale;
canvas.height= origImg.height * scale;
ctx.drawImage(origImg, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg");
}
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Image test</h1>
<img src="" id="imgOut" />
<label for="avatar">Choose a profile picture:</label>
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
<input type="button" id="resImg" onclick="resizeImg()" value="Resize" />
<input type="button" id="rotImg" onclick="rotateImg()" value="Rotate" />
</body>
</html>
As you have a part in onFilePicked() where you store something about the images:
let image = {
thumbnail: '/img/spinner.gif'
};
this.images.push(image);
and later update the same objects in loadImage() (well, an event handler in it) as
image.thumbnail = this.resizeImage(img, 400, 300);
image.large = this.resizeImage(img, 1280, 960);
It could be simply extended to
image.original = img;
image.thumbnail = this.resizeImage(img, 400, 300);
image.large = this.resizeImage(img, 1280, 960);
Starting from this point, the objects in your images array would have an original field, storing the original, non-resized variant of the image.

Resize image from input to upload

I've been struggled with this problem for couple hours. I want to resize an image from an input tag and then upload it to the server. Here is my attempt.
My input element:
<Input type="file" name="file" onChange={this.handleLoadAvatar} />
My handleLoadAvatar function:
handleLoadAvatar(e) {
var file = e.target.files[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = (e) => {
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 300;
var MAX_HEIGHT = 300;
var width = img.width; // GET STUCK HERE
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
this.setState({previewSrc: dataurl});
}
I'm using ReactJS for my project. I got stuck at the line with the comment above where I can't get the image's width. I tried this solution at HTML5 Pre-resize images before uploading but this seems not to work for me. Can anybody point out what's wrong with my code and how to fix it? Thanks a bunch!
The problem is that you aren't waiting for the image to load before accessing its width and height.
As you are waiting for the reader, you should do the same for the img:
handleLoadAvatar(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = (e) => {
var img = document.createElement("img");
img.onload = () => {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 300;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
this.setState({previewSrc: dataurl});
}
img.src = e.target.result;
}
reader.readAsDataURL(file);
}

HTML5 Canvas scaling an image animation

I've created a straight forward linear HTML5 animation but I now want the image to continuously scale bigger then smaller until the end of the canvas' height.
What's the best way to do this?
Here's a JSFIDDLE
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame;
var canvas = document.getElementById('monopoly-piece');
var context = canvas.getContext('2d');
var img = document.createElement("img");
img.src = "images/tophat.png";
img.shadowBlur = 15;
img.shadowColor = "rgb(0, 0, 0)";
var xSpeed = 0; //px per ms
var ySpeed = 0.15;
function animate(nowTime, lastTime, xPos, yPos) {
// update
if ((img.style.height + yPos) > canvas.height) {
xPos = 0;
yPos = 0;
}
var timeDelta = nowTime - lastTime;
var xDelta = xSpeed * timeDelta;
var yDelta = ySpeed * timeDelta;
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// shadow
context.shadowOffsetX = 3;
context.shadowOffsetY = 7;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
//draw img
context.drawImage(img, xPos, yPos);
if (yPos > canvas.height - img.height ) {
addMarker();
}
else {
requestAnimationFrame(
function(timestamp){
animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta);
}
);
}
}
animate(0, 0, -10, 0);
Here is my current code which animates an image from the top of the canvas element to the bottom and then stops.
Thanks.
context.DrawImage has additional parameters that let you scale your image to your needs:
// var scale is the scaling factor to apply between 0.00 and 1.00
// scale=0.50 will draw the image half-sized
var scale=0.50;
// var y is the top position on the canvas where you want to drawImage your image
var y=0;
context.drawImage(
// draw img
img,
// clip a rectangular portion from img
// starting at [top,left]=[0,0]
// and with width,height == img.width,img.height
0, 0, img.width, img.height,
// draw that clipped portion of of img on the canvas
// at [top,left]=[0,y]
// with width scaled to img.width*scale
// and height scaled to img.height*scale
0, y, img.width*scale, img.height*scale
)
Here's an example you can start with and fit to your own design needs:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var scale = 1;
var scaleDirection = 1
var iw, ih;
var y = 1;
var yIncrement = ch / 200;
var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start() {
iw = img.width;
ih = img.height;
requestAnimationFrame(animate);
}
function animate(time) {
if (scale > 0) {
requestAnimationFrame(animate);
}
ctx.clearRect(0, 0, cw, ch);
ctx.drawImage(img, 0, 0, iw, ih, 0, y, iw * scale / 100, ih * scale / 100);
scale += scaleDirection;
if (scale > 100) {
scale = 100;
scaleDirection *= -1;
}
y += yIncrement;
}
$("#test").click(function() {
scale = y = scaleDirection = 1;
requestAnimationFrame(animate);
});
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="test">Animate Again</button>
<br>
<canvas id="canvas" width=80 height=250></canvas>

Loader image not showing up when canvas rotating and resizing operation is going on selected file

I have created sample code here http://jsfiddle.net/kamlesh_bhure/YpejU/ where i am rotating image and resizing it as per max height and width.
Before starting this process I am showing mask with loading image and hiding it after completing it. But I am not able to see this loader on mobile device or on desktop browser even though I used large image.
Also I want to show loading image till browser complete its rendering of processed image.
Thanks in advance.
<!-- HTML Code -->
<div id="mask" class="newLoaderMask">
<img src="http://jimpunk.net/Loading/wp-content/uploads/loading1.gif" width="200" id="loader" />
</div>
<input type="file" accept="image/*" id="takePictureField" />
<div class="captureInsuPanel">
<img id="yourimage" class="imgWeightHght" width="500" />
</div>
<canvas id="hidden_canvas_old"></canvas>
<canvas id="hidden_canvas_new"></canvas>
<style>
#yourimage {
width:100%;
}
.imgWeightHght {
height: 290px !important;
width: 220px !important;
}
.captureInsuPanel img {
height: auto;
width: auto;
}
.newLoaderMask {
display: none;
background: #E5E5E5;
position: fixed;
left: 0;
top: 0;
z-index: 10;
width: 100%;
height: 100%;
opacity: 0.8;
z-index: 999;
}
</style>
<script>
//Js Code
$(document).ready(function () {
$("#takePictureField").on("change", gotPic);
});
function gotPic(event) {
if (event.target.files.length == 1 && event.target.files[0].type.indexOf("image/") == 0) {
var image = event.target.files[0];
$("#yourimage").attr("src", URL.createObjectURL(image));
drawRotatedImage(image, 90, 800, 1000);
}
}
function drawRotatedImage(image, angle, max_width, max_height) {
//show loading mask
$('#mask').show();
var fileLoader = new FileReader(),
imageObj = new Image();
if (image.type.indexOf("image/") == 0) {
fileLoader.readAsDataURL(image);
} else {
alert('File is not an image');
}
fileLoader.onload = function () {
var data = this.result;
imageObj.src = data;
};
fileLoader.onabort = function () {
alert("The upload was aborted.");
};
fileLoader.onerror = function () {
alert("An error occured while reading the file.");
};
// set up the images onload function which clears the hidden canvas context,
// draws the new image then gets the blob data from it
imageObj.onload = function () {
var imgWidth = this.width;
var imgHeight = this.height;
rotateAndResize(this, imgWidth, imgHeight);
};
function rotateAndResize(image, imgWidth, imgHeight) {
var canvas = document.getElementById("hidden_canvas_old"),
ctx = canvas.getContext("2d");
var widthHalf = imgWidth / 2,
heightHalf = imgHeight / 2;
canvas.width = imgWidth;
canvas.height = imgWidth;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(angle * Math.PI / 180);
ctx.drawImage(image, -widthHalf, -widthHalf);
ctx.restore();
var tempCanvas = document.getElementById("hidden_canvas_new"),
tCtx = tempCanvas.getContext("2d");
tempCanvas.width = imgHeight;
tempCanvas.height = imgWidth;
/*
* Crop rotated image from old canvas to remove white space
* So that canvas will have only image content without extra padding
*/
tCtx.drawImage(canvas, canvas.width - imgHeight, 0, imgHeight, imgWidth, 0, 0, imgHeight, imgWidth);
tCtx.restore();
/**
* Resizing Rotated image
*/
// calculate the width and height, constraining the proportions
if (imgWidth > imgHeight) {
if (imgWidth > max_width) {
imgHeight = Math.round(imgHeight *= max_width / imgWidth);
imgWidth = max_width;
}
} else {
if (imgWidth > max_height) {
imgWidth = Math.round(imgWidth *= max_height / imgHeight);
imgHeight = max_height;
}
}
var tempCanvasTemp = tempCanvas;
tempCanvas.remove();
canvas.remove();
var tempCanvas1 = document.createElement("canvas"),
tCtx1 = tempCanvas1.getContext("2d");
tempCanvas1.id = 'hidden_canvas_new';
//tempCanvas1.style.display = 'none';
tempCanvas1.width = imgHeight;
tempCanvas1.height = imgWidth;
tCtx1.drawImage(tempCanvasTemp, 0, 0, imgHeight, imgWidth);
tCtx1.restore();
document.body.appendChild(tempCanvas1);
$("#yourimage").attr("src", tempCanvas1.toDataURL('image/jpeg'));
}
//hide loading mask
$('#mask').hide();
}
</script>
You are hiding your loading div #mask in drawRotatedImage function but you should hide it in rotateAndResize function where you are drawing your picture to canvas.
CODE:
$(document).ready(function () {
$("#takePictureField").on("change", gotPic);
});
function gotPic(event) {
if (event.target.files.length == 1 && event.target.files[0].type.indexOf("image/") == 0) {
var image = event.target.files[0];
$("#yourimage").attr("src", URL.createObjectURL(image));
drawRotatedImage(image, 90, 800, 1000);
}
}
function drawRotatedImage(image, angle, max_width, max_height) {
$('#mask').show();
var fileLoader = new FileReader(),
imageObj = new Image();
if (image.type.indexOf("image/") == 0) {
fileLoader.readAsDataURL(image);
} else {
alert('File is not an image');
}
fileLoader.onload = function () {
var data = this.result;
imageObj.src = data;
};
fileLoader.onabort = function () {
alert("The upload was aborted.");
};
fileLoader.onerror = function () {
alert("An error occured while reading the file.");
};
// set up the images onload function which clears the hidden canvas context,
// draws the new image then gets the blob data from it
imageObj.onload = function () {
var imgWidth = this.width;
var imgHeight = this.height;
rotateAndResize(this, imgWidth, imgHeight);
};
function rotateAndResize(image, imgWidth, imgHeight) {
var canvas = document.getElementById("hidden_canvas_old"),
ctx = canvas.getContext("2d");
var widthHalf = imgWidth / 2,
heightHalf = imgHeight / 2;
canvas.width = imgWidth;
canvas.height = imgWidth;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(angle * Math.PI / 180);
ctx.drawImage(image, -widthHalf, -widthHalf);
ctx.restore();
var tempCanvas = document.getElementById("hidden_canvas_new"),
tCtx = tempCanvas.getContext("2d");
tempCanvas.width = imgHeight;
tempCanvas.height = imgWidth;
/*
* Crop rotated image from old canvas to remove white space
* So that canvas will have only image content without extra padding
*/
tCtx.drawImage(canvas, canvas.width - imgHeight, 0, imgHeight, imgWidth, 0, 0, imgHeight, imgWidth);
tCtx.restore();
/**
* Resizing Rotated image
*/
// calculate the width and height, constraining the proportions
if (imgWidth > imgHeight) {
if (imgWidth > max_width) {
imgHeight = Math.round(imgHeight *= max_width / imgWidth);
imgWidth = max_width;
}
} else {
if (imgWidth > max_height) {
imgWidth = Math.round(imgWidth *= max_height / imgHeight);
imgHeight = max_height;
}
}
var tempCanvasTemp = tempCanvas;
tempCanvas.remove();
canvas.remove();
var tempCanvas1 = document.createElement("canvas"),
tCtx1 = tempCanvas1.getContext("2d");
tempCanvas1.id = 'hidden_canvas_new';
//tempCanvas1.style.display = 'none';
tempCanvas1.width = imgHeight;
tempCanvas1.height = imgWidth;
tCtx1.drawImage(tempCanvasTemp, 0, 0, imgHeight, imgWidth);
tCtx1.restore();
document.body.appendChild(tempCanvas1);
$("#yourimage").attr("src", tempCanvas1.toDataURL('image/jpeg'));
$('#mask').hide();
}
}
DEMO FIDDLE
NOTE: While testing fiddle found out one more issue, if we try to upload image second time second canvas in not updating with new image. Hope you need to work on this.

Categories