I'm trying to rotate an image inside a HTML canvas
. The rotating does work, but however, each single rotation time, the corners of the image are cut/clipped off. This is wrong because the whole uploaded image should be intact after rotating.
Some important details:
- In my specific usecase I do not have access to the image data itself. So the image which is uploaded by the user will be processed and drawn on a HTML canvas. I only can access the HTML canvas element, not the uploaded image itself. This is how the system works.
- The canvas width and height should be exact the same as the width & height of the uploaded image
- The canvas itself should maintain its dimensions and should not be rotated, only the image in it should be rotated.
- No CSS, should only be archieved with JavaScript because the rotated canvas image will be uploaded to the server.
So the problem here is that each time I want to rotate the image 45 degrees, the corners of the image inside the HTML canvas are clipped/cutted off. Obvious this is not correct since the whole image should be rotated. I can't figure out what I did wrong so maybe someone can help me futher?
https://jsfiddle.net/d5zurxq2/
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" width=250 height=250></canvas>
<br /><br /><br />
<button type="button" id="rotateLeft">Rotate 45 degrees left</button>
#imageCanvas {
width: 350px;
height: 250px;
background-color: rgba(158, 167, 184, 0.2)
}
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext("2d");
function handleImage(e){
var reader = new FileReader();
reader.onload = function(e) {
var preview = document.createElement('img');
preview.onload = function()
{
canvas.width = preview.width;
canvas.height = preview.height;
canvas.getContext('2d').drawImage(preview, 0, 0);
};
preview.src = reader.result;
};
reader.readAsDataURL(e.target.files[0]);
}
document.getElementById('rotateLeft').addEventListener('click', rotateImage,
false);
function rotateImage() {
var w = ctx.canvas.width;
var h = ctx.canvas.height;
var ww = w / 2;
var hh = h / 2;
ctx.save();
ctx.globalCompositeOperation = "copy";
ctx.translate(ww, hh);
ctx.rotate((Math.PI / 180) * 45);
ctx.drawImage(canvas, -canvas.width/2, -canvas.height/2);
ctx.restore();
}