I am creating a website in which I am showing some images. I have gone through many websites and there is no result.
HTML:
<head></head>
<body onload=init()>
<img id="imgID" src="images/buttons/panda-wall.jpg" alt="panda wall" width="100" height="100"><br></br>
<canvas id="myCanvas" height="400px" width="400px" style="border:1px solid"></canvas>
<button onclick="rotateImage()">Clear canvas</button>
</body>
JavaScript:
function init()
{
var c = document.getElementById("myCanvas");
var context = c.getContext('2d');
var img = document.getElementById("imgID");
context.drawImage(img,0,0,c.width, c.height);
}
function rotateImage()
{
var c = document.getElementById("myCanvas");
var context = c.getContext('2d');
var img = document.getElementById("imgID");
context.save();
// Translate
context.translate(200, 200);
// Scale
context.scale(2,2);
// Rotate it
context.rotate(10*Math.PI/180);
context.translate(-200, -200);
context.drawImage(img,0,0);
// Finally draw the image data from the temp canvas.
context.restore();
}
Thanks in advance.
Update:- I have fixed my problem with the below changes:
function rotateImage()
{
var c=document.getElementById("myCanvas");
var context = c.getContext('2d');
var img = document.getElementById("imgID");
//clear the context object rectangle.
context.clearRect(0, 0, c.width, c.height);
//Save the context object.
context.save();
// Translate
context.translate(c.width/2, c.height/2);
// Rotate it with 90 degree
context.rotate(90*Math.PI/180);
//Translate the image on the basis of the center of the canvas.
context.translate(-(c.width/2), -(c.height/2));
// Draw the Image.
context.drawImage(img,0,0, c.width,c.height);
// Finally draw the image data from the temp canvas.
context.restore();
}
But still I am having issues to find the exact possition of my co-ordinates for larger images (e.g. width:800px and height:1280px). for small Images (e.g width:240 and height:400) I am using the below logic for getting X and Y co-ordinate values:
X=(Image.width/canvas.width)*current_mousePosition.X; Y=(Image.height/canvas.height)*current_mousePosition.Y;
but this logic fails for the larger images, width and height as mentioned above. Can anyone please help me what will be the logic to get the exact co-ordinates of the current mouse position respective to the original Image. Is there any default logic available for all in all size images? Any help, in terms of link or idea will be greatly appreciated. Thanks in advance