I am trying to make the canvas area and image fill the viewport without the image stretching and retain its aspect ratio when you resize the page. Below is my current code.
var ctx = $("#demo")[0].getContext("2d"),
img = new Image(),
radius = 35,
blurryImageSrc = "https://s9.postimg.cc/u9nsmzlwf/image.jpg";
img.src = blurryImageSrc;
$(img).on("load", function() {
resizeCanvas();
$("#demo").on("mousemove", function(e) {
erase(getXY(e));
});
$("#reset").on("click", function() {
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "destination-out";
});
ctx.drawImage(img, 0, 0, window.innerWidth, window.innerHeight);
ctx.globalCompositeOperation = "destination-out";
});
function getXY(e) {
var r = $("#demo")[0].getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
}
function erase(pos) {
ctx.beginPath();
ctx.arc(pos.x, pos.y, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
}
var can = document.getElementById('demo');
function resizeCanvas() {
can.style.width = window.innerWidth + 'px';
setTimeout(function() {
can.style.height = window.innerHeight + 'px';
}, 0);
}
window.onresize = resizeCanvas;
resizeCanvas();
https://jsfiddle.net/65fph0mn/8/
To retain the image's correct proportions, you need to query it's 'natural' width and height. The image object itself has two properties for this purpose: naturalWidth and naturalHeight.
As the image finished loading you must decide by which factor to scale the image based on the dimensions of the browser window and the longer side of your image.
Let's have a look at a simple example. Say your browser window's width is 1200 pixel and the image 250. If we now divide 1200 by 250 we get 4.8 - that's the factor we need to multiply the image's width and height to fill the current browser window in one direction while maintaining it's correct aspect ratio.
Here's an example:
var ctx = $("#demo")[0].getContext("2d"),
img = new Image(),
radius = 35,
blurryImageSrc = "https://s9.postimg.cc/u9nsmzlwf/image.jpg";
/// setup logic
img.src = blurryImageSrc;
$(img).on("load", function() {
resizeCanvas();
});
var can = document.getElementById('demo');
function resizeCanvas() {
can.width = window.innerWidth;
can.height = window.innerHeight;
if (img.width > 0) {
let factor = can.width / img.naturalWidth * img.naturalHeight > window.innerHeight ? can.height / img.naturalHeight : can.width / img.naturalWidth;
ctx.drawImage(img, 0, 0, img.naturalWidth * factor, img.naturalHeight * factor);
}
}
window.onresize = resizeCanvas;
resizeCanvas();
body {
background: lightgrey;
margin: 0;
}
.container {
position: relative;
background: blue;
width: 100vw;
height: 100vh;
}
#demo {
cursor: crosshair;
width: 100vw;
height: 100vh;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div class="container">
<canvas id="demo" width=640 height=640></canvas>
</div>
Here I'm waiting for the image to load. Then I can add the eventlistener for window resize and call the function resizeCanvas. This function will then resize the canvas and paint the image in the canvas.
The image must be repainted every time the window is resized.
To keep the aspect ratio the height of the image is calculated from the scaled width.
const canvas = document.getElementById('demo');
var ctx = canvas.getContext("2d"),
img = new Image(),
blurryImageSrc = "https://s9.postimg.cc/u9nsmzlwf/image.jpg";
img.src = blurryImageSrc;
img.addEventListener("load", e => {
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
});
function paint() {
var newHeight = Math.round(img.width/canvas.width*img.height);
ctx.drawImage(img, 0, 0, img.width, newHeight, 0, 0, canvas.width, canvas.height);
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
paint();
}
body {
background: lightgrey;
margin: 0;
}
.container {
position: relative;
background: blue;
width: 100vw;
height: 100vh;
}
#demo {
cursor: crosshair;
width: 100vw;
height: 100vh;
}
<div class="container">
<canvas id="demo" width="640" height="640"></canvas>
</div>
Related
What I want to do
Set background-size:cover-like effect on a canvas image
Re-draw a canvas image as a window is resized (responsive)
What I tried
I tried 2 ways below. Neither works.
Simulation background-size: cover in canvas
How to set background size cover on a canvas
Issue
The image's aspect ratio is not fixed.
I am not sure but the image does not seem to be re-rendered as a window is resized.
My code
function draw() {
// Get <canvas>
const canvas = document.querySelector('#canvas');
// Canvas
const ctx = canvas.getContext('2d');
const cw = canvas.width;
const ch = canvas.height;
// Image
const img = new Image();
img.src = 'https://source.unsplash.com/WLUHO9A_xik/1600x900';
img.onload = function() {
const iw = img.width;
const ih = img.height;
// 'background-size:cover'-like effect
const aspectHeight = ih * (cw / iw);
const heightOffset = ((aspectHeight - ch) / 2) * -1;
ctx.drawImage(img, 0, heightOffset, cw, aspectHeight);
};
}
window.addEventListener('load', draw);
window.addEventListener('resize', draw);
canvas {
display: block;
/* canvas width depends on parent/window width */
width: 90%;
height: 300px;
margin: 0 auto;
border: 1px solid #ddd;
}
<canvas id="canvas"></canvas>
The canvas width / height attributes do not reflect it's actual size in relation to it being sized with CSS. Given your code, cw/ch are fixed at 300/150. So the whole calculation is based on incorrect values.
You need to use values that actually reflect it's visible size. Like clientWidth / clientHeight.
A very simple solution is to update the canvas width/height attributes before using them for any calculations. E.g.:
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
Full example:
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
// only load the image once
const img = new Promise(r => {
const img = new Image();
img.src = 'https://source.unsplash.com/WLUHO9A_xik/1600x900';
img.onload = () => r(img);
});
const draw = async () => {
// resize the canvas to match it's visible size
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
const loaded = await img;
const iw = loaded.width;
const ih = loaded.height;
const cw = canvas.width;
const ch = canvas.height;
const f = Math.max(cw/iw, ch/ih);
ctx.setTransform(
/* scale x */ f,
/* skew x */ 0,
/* skew y */ 0,
/* scale y */ f,
/* translate x */ (cw - f * iw) / 2,
/* translate y */ (ch - f * ih) / 2,
);
ctx.drawImage(loaded, 0, 0);
};
window.addEventListener('load', draw);
window.addEventListener('resize', draw);
.--dimensions {
width: 90%;
height: 300px;
}
.--border {
border: 3px solid #333;
}
canvas {
display: block;
margin: 0 auto;
}
#test {
background: url(https://source.unsplash.com/WLUHO9A_xik/1600x900) no-repeat center center;
background-size: cover;
margin: 1rem auto 0;
}
<canvas id="canvas" class="--dimensions --border"></canvas>
<div id="test" class="--dimensions --border"></div>
First, load only once your image, currently you are reloading it every time the page is resized.
Then, your variables cw and ch will always be 300 and 150 since you don't set the size of your canvas. Remember, the canvas has two different sizes, its layout one (controlled by CSS) and its buffer one (controlled by its .width and .height attributes).
You can retrieve the layout values through the element's .offsetWidth and .offsetHeight properties.
Finally, your code does a contain image-sizing. To do a cover, you can refer to the answers you linked to, and particularly to K3N's one
{
// Get <canvas>
const canvas = document.querySelector('#canvas');
// Canvas
const ctx = canvas.getContext('2d');
// Image
const img = new Image();
img.src = 'https://source.unsplash.com/WLUHO9A_xik/1600x900';
function draw() {
// get the correct dimension as calculated by CSS
// and set the canvas' buffer to this dimension
const cw = canvas.width = canvas.offsetWidth;
const ch = canvas.height = canvas.offsetHeight;
if( !inp.checked ) {
drawImageProp(ctx, img, 0, 0, cw, ch, 0, 0);
}
}
img.onload = () => {
window.addEventListener('resize', draw);
draw();
};
inp.oninput = draw;
}
// by Ken Fyrstenberg https://stackoverflow.com/a/21961894/3702797
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
if (arguments.length === 2) {
x = y = 0;
w = ctx.canvas.width;
h = ctx.canvas.height;
}
// default offset is center
offsetX = typeof offsetX === "number" ? offsetX : 0.5;
offsetY = typeof offsetY === "number" ? offsetY : 0.5;
// keep bounds [0.0, 1.0]
if (offsetX < 0) offsetX = 0;
if (offsetY < 0) offsetY = 0;
if (offsetX > 1) offsetX = 1;
if (offsetY > 1) offsetY = 1;
var iw = img.width,
ih = img.height,
r = Math.min(w / iw, h / ih),
nw = iw * r, // new prop. width
nh = ih * r, // new prop. height
cx, cy, cw, ch, ar = 1;
// decide which gap to fill
if (nw < w) ar = w / nw;
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // updated
nw *= ar;
nh *= ar;
// calc source rectangle
cw = iw / (nw / w);
ch = ih / (nh / h);
cx = (iw - cw) * offsetX;
cy = (ih - ch) * offsetY;
// make sure source rectangle is valid
if (cx < 0) cx = 0;
if (cy < 0) cy = 0;
if (cw > iw) cw = iw;
if (ch > ih) ch = ih;
// fill image in dest. rectangle
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}
canvas {
display: block;
/* canvas width depends on parent/window width */
width: 90%;
height: 300px;
margin: 0 auto;
border: 1px solid #ddd;
background-image: url('https://source.unsplash.com/WLUHO9A_xik/1600x900');
background-size: cover;
background-repeat: no-repeat;
}
<label><input id="inp" type="checkbox">show CSS rendering</label>
<canvas id="canvas"></canvas>
I would like the rectangle to move on the canvas and not copy every time.
It draws it but then the rectangle stays there.
I am a beginner with the canvas so if it is an epic fail then be prepared.
The codepen is at LINK.
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var boxWidth = 50;
var boxHeight = 50;
var bX = WIDTH / 2 - boxWidth / 2;
var bY = HEIGHT / 2 - boxHeight / 2;
function render() {
ctx.fillStyle = "white";
ctx.rect(bX, bY, boxWidth, boxHeight);
ctx.fill();
}
function control() {
bX++;
}
function main() {
control();
render();
}
main();
var run = setInterval(main, 10)
canvas {
width: 400px;
height: 400px;
background-color: black;
}
div {
text-align: center;
}
<div>
<canvas width="400px" height="400px" background-color="black" id="canvas"></canvas>
</div>
Repaint your canvas before drawing the rectangle each time - think about it. Its all done in layers.
The rectangle is "staying there" because you aren't replacing the rectangle your drew last time.
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var boxWidth = 50;
var boxHeight = 50;
var bX = WIDTH / 2 - boxWidth / 2;
var bY = HEIGHT / 2 - boxHeight / 2;
function render() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); //use clear rect instead
ctx.fillStyle = "white";
ctx.fillRect(bX, bY, boxWidth, boxHeight); //use fillRect instead of fill()
}
function control() {
bX++;
}
(function main() {
control();
render();
requestAnimationFrame(()=>main());
})()
canvas {
width: 400px;
height: 400px;
background-color: black;
}
div {
text-align: center;
}
<html>
<head></head>
<body>
<div>
<canvas width="400px" height="400px" background-color="black" id="canvas"></canvas>
</div>
</body>
</html>
Also have a look at the requestAnimationFrame() method as opposed to setInterval - it syncs up with the window's javascript timer and is less likely to cause problems.
I am trying to display simple text on the screen via update() and setInterval() functions, but it's not working. Note that I create a canvas on which I want the text to be displayed. Please , check the code below.
var canvas, canvasContext;
window.onload = function() {
canvas = document.getElementById('theCanvas');
canvasContext = canvas.getContext('2d');
var fps = 30;
setInterval(update, 1000 / fps);
}
function update() {
drawText();
}
function drawText() {
canvasContext.fillStyle = 'black';
canvasContext.font = 'bold 40px Monospace';
canvasContext.fillText('POC ......', 150, 150);
}
#canvasHolder {
position: absolute;
left: 0px;
top: 0px;
}
#theCanvas {
background-color: lightgreen;
width: 100pc;
height: 100pc;
}
<div id="canvasHolder">
<canvas id="theCanvas"></canvas>
</div>
The issue is that the canvas is being stretched to fill the element. Both the canvas itself and the canvas element have a size. If you don't specify the size of the canvas (you haven't), it defaults to 300x150. When the size of the element and the canvas don't match, the canvas content is scaled to fit into the element.. So the text is being drawn, it's just really big; scroll to the right and down and you'll find it.
My guess is that you meant for the canvas and the element to be the same size. If so, you need to set the size of the canvas. You can do that with width and height attributes on the canvas element, but those values will be in pixels, not picas as in your CSS. So we do it dynamically by getting the computed width and height of the element (because they'll come back to us in pixels), and then setting those values for the width and height attributes of the canvas:
// Set the canvas size to match the element size
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
Updated snippet:
var canvas, canvasContext;
window.onload = function() {
canvas = document.getElementById('theCanvas');
// Set the canvas size to match the element size
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
canvasContext = canvas.getContext('2d');
canvasContext.canvas.width = canvas.width;
canvasContext.canvas.height = canvas.height;
var fps = 30;
setInterval(update, 1000 / fps);
};
function update() {
drawText();
}
function drawText() {
canvasContext.fillStyle = 'black';
canvasContext.font = 'bold 40px Monospace';
canvasContext.fillText('POC ......', 150, 150);
}
#canvasHolder {
position: absolute;
left: 0px;
top: 0px;
}
#theCanvas {
background-color: lightgreen;
width: 100pc;
height: 100pc;
}
<div id="canvasHolder">
<canvas id="theCanvas"></canvas>
</div>
Note that right now, you're just redrawing it at the same location every time, but I assume moving it was your next task...
The text is already rendered but if you want to animate your text then you have to change your draw function because each time you are drawing your text in the same position -
function drawText() {
canvasContext.fillStyle = 'black';
canvasContext.font = 'bold 40px Monospace';
canvasContext.fillText('POC ......', 150, 150); //here you have given the fixed position.
}
and you have to clear your canvas before rendering your text in new position-
please refer -
How to clear the canvas for redrawing
I have written code which will capture photo using camera and show it as snapshot. But before showing it as snapshot I am resizing image and rotate (if captured image is horizontal). This re-sized image is binary content which is less in size so uploading it on server becomes quick. Now I want to optimize code so that it will work better with low memory.
Problem facing:
On mobile device, sometimes chrome browser showing "unable to complete previous operation due to low memory".
Could be possible solution (i think but with question):
Processing image in chunks, will make think work better?
Thanks in advance for your help.
You may see working code here
or
Working sample code
<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>
<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/*" capture="camera" id="takePictureField" />
<div class="captureInsuPanel">
<img id="yourimage" class="imgWeightHght" width="500" />
</div>
<script>
$(document).ready(function () {
$("#takePictureField").on("change", gotPic);
});
var max_width = 1000;
var max_height = 1000;
function gotPic(event) {
if (event.target.files.length == 1 && event.target.files[0].type.indexOf("image/") == 0) {
var image = event.target.files[0];
processCapturedImage(image, 90, max_width, max_height, $("#yourimage"));
}
}
function processCapturedImage(image, angle, max_width, max_height, thumbNailImage) {
$('#mask').show();
//create a hidden canvas object we can use to create new rotated image
var canvas = document.createElement('canvas');
canvas.id = "hidden_canvas_old";
canvas.style.display = "none";
document.body.appendChild(canvas);
//create a hidden canvas object we can use to create the new cropped &/or resized image data
var canvas_new = document.createElement('canvas');
canvas_new.id = "hidden_canvas_new";
canvas_new.style.display = "none";
document.body.appendChild(canvas_new);
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;
if (imgWidth > imgHeight) {
//Rotate horizontal image to vertical and resizing is needed
rotateAndResize(this, imgWidth, imgHeight, angle, max_width, max_height, thumbNailImage);
} else {
//no need to rotate only resizing is needed
resize(this, imgWidth, imgHeight, max_width, max_height, thumbNailImage);
}
};
imageObj.onabort = function () {
alert("Image load was aborted.");
};
imageObj.onerror = function () {
alert("An error occured while loading image.");
};
}
function rotateAndResize(image, imgWidth, imgHeight, angle, max_width, max_height, thumbNailImage) {
var canvas = document.getElementById("hidden_canvas_old"),
ctx = canvas.getContext("2d");
var widthHalf = imgWidth / 2,
heightHalf = imgHeight / 2;
canvas.width = imgWidth;
canvas.height = imgWidth;
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//set coordinate to rotate canvas
ctx.translate(canvas.width / 2, canvas.height / 2);
//rotate canvas with given angle
ctx.rotate(angle * Math.PI / 180);
//draw image on rotated canvas with given coordinate
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();
//Delete unwanted canvas to reduce page size
canvas.remove();
/**
* 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();
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);
thumbNailImage.attr("src", tempCanvas1.toDataURL('image/jpeg'));
$('#mask').hide();
}
function resize(image, imgWidth, imgHeight, max_width, max_height, thumbNailImage) {
/**
* Resizing image
*/
// calculate the width and height, constraining the proportions
if (imgWidth > imgHeight) {
if (imgWidth > max_width) {
//height *= max_width / width;
imgHeight = Math.round(imgHeight *= max_width / imgWidth);
imgWidth = max_width;
}
} else {
if (imgWidth > max_height) {
//width *= max_height / height;
imgWidth = Math.round(imgWidth *= max_height / imgHeight);
imgHeight = max_height;
}
}
var tempCanvas = document.getElementById("hidden_canvas_new"),
tCtx = tempCanvas.getContext("2d");
tempCanvas.width = imgWidth;
tempCanvas.height = imgHeight;
tCtx.drawImage(image, 0, 0, imgWidth, imgHeight);
thumbNailImage.attr("src", tempCanvas.toDataURL('image/jpeg'));
$('#mask').hide();
}
</script>
Try using MediaDevices.getUserMedia() (documentation) for browsers which support it, you don't need to resize the photo as you can request the size of the photo.
Several examples:
http://www.html5rocks.com/en/tutorials/getusermedia/intro/
https://github.com/addyosmani/getUserMedia.js
as far as I know getUserMedia() supports the maximum resolution of the video
So if you have a 12M camera, but video is maximum 720p then you can set image quality to maximum 720p
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.