我正在创建一个显示一些图像的网站。我浏览了很多网站,都没有结果。
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();
}
提前致谢。
更新:- 我已通过以下更改解决了我的问题:
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();
}
但是我仍然无法找到较大图像的坐标的确切位置(例如宽度:800px 和高度:1280px)。对于小图像(例如宽度:240 和高度:400),我使用以下逻辑来获取 X 和 Y 坐标值:
X=(Image.width/canvas.width)*current_mousePosition.X; Y=(Image.height/canvas.height)*current_mousePosition.Y;
但是对于上面提到的较大的图像、宽度和高度,这个逻辑是失败的。谁能帮助我获得当前鼠标位置相对于原始图像的确切坐标的逻辑是什么。是否有适用于所有尺寸图像的默认逻辑?在链接或想法方面的任何帮助将不胜感激。提前致谢