【发布时间】:2012-11-08 15:48:48
【问题描述】:
我正在创建一个展示一些图片的网站。浏览了很多网站都没有结果。
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();
}
但我仍然无法找到较大图像的坐标的确切位置(例如宽度:800 像素和高度:1280 像素)。对于小图像(例如宽度:240 和高度:400),我使用以下逻辑来获取 X 和 Y 坐标值:
X=(Image.width/canvas.width)*current_mousePosition.X; Y=(Image.height/canvas.height)*current_mousePosition.Y;
但是对于上面提到的较大的图像、宽度和高度,此逻辑失败。谁能帮我获取当前鼠标位置相对于原始图像的确切坐标的逻辑是什么。是否有适用于所有尺寸图像的默认逻辑?在链接或想法方面的任何帮助将不胜感激。提前致谢
【问题讨论】:
-
这里没有有意义的代码 -
rotateImage()和rotateCanvas()定义在哪里? -
那是 HTML 和一点 JS。
-
我已经更新了正确的信息
-
你应该在 context.restore() 之前使用 context.save() 吗?
-
我关注了stackoverflow.com/questions/4649836/…链接,但没有成功
标签: php javascript html canvas image-rotation