gpt4 book ai didi

php - HTML Canvas 中的图像不旋转

转载 作者:行者123 更新时间:2023-11-28 09:34:32 27 4
gpt4 key购买 nike

我正在创建一个网站,在其中显示一些图像。我查了很多网站都没有结果。

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;

但是对于如上所述的较大图像、宽度和高度,这种逻辑失败。任何人都可以帮助我获取当前鼠标位置相对于原始图像的确切坐标的逻辑是什么。是否有适用于所有尺寸图像的默认逻辑?任何链接或想法方面的帮助将不胜感激。提前致谢

最佳答案

img.onload函数中绘制它。

关于php - HTML Canvas 中的图像不旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280104/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com