gpt4 book ai didi

javascript - 为什么这张图片没有旋转?

转载 作者:行者123 更新时间:2023-11-30 09:12:13 25 4
gpt4 key购买 nike

我想在绘制之前在 html Canvas 上旋转图像。我使用了以下代码(ctx 是 Canvas 上下文):

ctx.rotate(Math.PI / 4);
var img = new Image();
img.src = "Test.png";
img.onload = function()
{
ctx.drawImage(img, 0, 0);
}
ctx.beginPath();
ctx.resetTransform();

我希望图像旋转 45°。如果我省略最后一行,实际上就是这种情况。但是如果我包括最后一行,则图像是在没有旋转的情况下绘制的。为什么会这样?我预计 beginPath() 之后的所有内容都与之前的绘图无关。

如何避免这种影响?我想在图像之后画东西,它们根本不应该旋转。

最佳答案

您的 onload 函数在图像加载时被异步触发。

其余代码在加载图像时运行,并在加载图像之前重置上下文。

你的代码是这样的:

Rotate canvas
Load an image "Test.png"
When the image loaded, run this code: { Draw the image }
While the image is loading...
Reset the rotation

要等待图像加载,请将完整的绘图代码移动到该函数:

var img = new Image();
img.src = "Test.png";
img.onload = function()
{
ctx.rotate(Math.PI / 4);
ctx.drawImage(img, 0, 0);
ctx.beginPath();
ctx.resetTransform();
//Draw something else after the image has loaded and drawn
}
//Draw something BEFORE image load

关于javascript - 为什么这张图片没有旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57741399/

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