尝试镜像画布上下文无法渲染画布

时间:2020-03-21 01:30:48

标签: javascript canvas

我尝试与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年中情况发生了如此大的变化,以至于在这里引入了重大变化?!?! (我想它根本不会改变!)

怎么了?

1 个答案:

答案 0 :(得分:1)

我用它来做你想做的事

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);
}
相关问题