gpt4 book ai didi

javascript - 尝试镜像 Canvas 上下文无法渲染 Canvas

转载 作者:行者123 更新时间:2023-12-02 21:24:07 24 4
gpt4 key购买 nike

当我跟随 this awesome mario bros tutorial 时,我正在尝试水平翻转 Canvas 。 。正如我在许多其他有关翻转 Canvas 的答案中看到的那样,我添加了这些行来更新上下文:

    define(name, x, y, width, height) {
const { image, } = this;
const buffer = document.createElement('canvas');
buffer.width = width;
buffer.height = height;

const context = buffer.getContext('2d');

context.scale(-1, 1); // <<< THIS ONE
context.translate(width, 0); // <<< AND THIS ONE

context.drawImage(
image,
x,
y,
width,
height, // what part of the image to draw
0, 0, width, height); // where to draw it
this.tiles.set(name, buffer); // store the info about the tile in our map
}

以前的代码运行得非常好。但是当我添加这些行并刷新浏览器时,整个 Canvas 都消失了!我无法想象自视频制作以来过去 2 1/2 年里事情发生了如此之大的变化,以至于在这里引入了重大变化?!?! (我想它根本不会改变!)

出了什么问题?

最佳答案

我用它来做你想做的事:

function horizontalFlip(img,x,y){
/* Move to x + image width */
context.translate(x+img.width, y);
/* scaleX by -1; this causes horizontal flip */
context.scale(-1,1);
/* Draw the image
No need for x,y since we've already translated */
context.drawImage(img,0,0);
/* Clean up - reset transformations to default */
context.setTransform(1,0,0,1,0,0);
}

此函数按预期工作,这里是 Sprite 的变体。

function flipSpriteHorizontal(img, x, y, spriteX, spriteY, spriteW, spriteH){
/* Move to x + image width
adding img.width is necessary because we're flipping from
the right side of the image so after flipping it's still at [x,y] */
context.translate(x + spriteW, y);

/* ScaleX by -1, this performs a horizontal flip */
context.scale(-1, 1);
/* Draw the image
No need for x,y since we've already translated */
context.drawImage(img,
spriteX, spriteY, spriteW, spriteH,
0, 0, spriteW, spriteH
);
/* Clean up - reset transformations to default */
context.setTransform(1, 0, 0, 1, 0, 0);
}

关于javascript - 尝试镜像 Canvas 上下文无法渲染 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60783648/

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