我尝试与this awesome mario bros tutorial一起水平翻转画布。正如我在有关翻转画布的许多其他答案中也看到的那样,我添加了以下几行来更新上下文:

    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
    }


以前,该代码非常出色。但是,当我添加这些行并刷新浏览器时,整个画布都消失了!自视频制作以来,我无法想象在过去的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/

10-12 00:13
查看更多