gpt4 book ai didi

javascript - 在 HTML Canvas 中单独旋转平铺图像

转载 作者:行者123 更新时间:2023-12-04 10:42:39 26 4
gpt4 key购买 nike

我的游戏中有一些代码可以在其 Canvas 中旋转图标,如下所示:

if (rotate > 0) {
context.translate(canvasWidth / 2, canvasHeight / 2);
context.rotate(rotate);
context.translate(-canvasWidth / 2, -canvasHeight / 2);
}

没有你以前没见过的东西。我还添加了一个功能,可以在更大的 Canvas 中平铺图标,如下所示:
var x = 0;
var y = 0;

for (var i = 0; i < totalUnits; i++) {
context.drawImage(img, x, y);

if (i != 0 && (i + 1) % level == 0) {
x = 0;
y += 72;
}

else {
x += 72;
}
}

注意变量 level可以是任意整数, totalUnits如果它大于 1,则是它的平方,例如,如果我指定 level作为 2,然后在我的 Canvas 上绘制了 4 个图像,2 个横向和 2 个向下。另请注意,我的图像始终为 72x72 像素,因此是上面的 72。同样,没有什么特别令人兴奋的。

我的困难是尝试旋转 Canvas 内的图像,以便根据 rotate 中传递的值旋转单个图像。 ,但不是整个 Canvas 本身。我尝试添加以下代码,其中包含许多排列替换上述对 context.drawImage 的调用在 for循环,到目前为止没有运气:
context.translate(72 / 2, 72 / 2);
context.rotate(rotate);
context.drawImage(img, x, y);
context.rotate(0);
context.translate(-72 / 2, -72 / 2);

为了帮助可视化我想要达到的效果,以下是当旋转设置为 0 时绘制的内容:

enter image description here

这是我希望 Canvas 上的平铺图像在旋转 45 度时的样子(例如):
enter image description here

我想指出的是,我并不是要旋转整个 Canvas ——我知道该怎么做,但这不是我想要达到的效果,因为我需要图标保持在它们各自的 x, y职位。此外,旋转整个 Canvas 会带来截止 Angular 挑战。

任何帮助将非常感激!

最佳答案

最简单的方法是覆盖当前的转换

ctx.setTransform(scale, 0, 0, scale, x, y); 
ctx.rotate(rotate);
ctx.drawImage(img, -img.width / 2, -img.height/ 2);

x 绘制图像中心, y ,旋转了 rotate附近 img居中,按 scale 缩放. 1 的规模是没有规模。

例如在清除 Canvas 之前重置为默认转换
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

因为在引擎盖下 ctx.rotate至少需要 1 个 sin 和 1 个 cos,12 个临时数字,然后是 12 个乘法和 8 个加法。如果缩放是统一的(x 和 y 的缩放相同),则使用简化的方法来创建矩阵会更快。请注意,如果比例始终为 1,则不需要比例`

此外,当图像加载时,您可以将旋转点设置为图像的属性。

当图像加载时设置偏移量
img.offset_x = - img.naturalWidth / 2;  // NOTE I use snake_case for the property names
img.offset_y = - img.naturalHeight / 2; // so that the names will never clash with
// future changes to the standard

渲染该图像
const ax = Math.cos(rotate) * scale;
const ay = Math.sin(rotate) * scale;
ctx.setTranform(ax, ay, -ay, ax, x, y);
ctx.drawImage(img, img.offset_x, img.offset_y);

关于javascript - 在 HTML Canvas 中单独旋转平铺图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59852447/

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