简体   繁体   English

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

[英]Attempting to mirror canvas context fails to render canvas

I'm attempting to flip my canvas horizontally as I follow along with this awesome mario bros tutorial .当我跟随这个很棒的马里奥兄弟教程时,我正在尝试水平翻转我的画布。 As I've also seen in many other answers about flipping a canvas, I added these lines updating the context:正如我在关于翻转画布的许多其他答案中也看到的那样,我添加了这些行来更新上下文:

    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
    }

The code, previously, worked awesomely.以前的代码工作得非常好。 But when I add these lines and refresh my browser, the entire canvas is gone!但是当我添加这些行并刷新浏览器时,整个画布都不见了! I can't imagine things have changed so much in the past 2 1/2 years since the video was made as to introduce a breaking change here?!?!我无法想象自视频制作以来的过去 2 1/2 年里事情发生了如此大的变化,以至于在这里引入了重大变化?!?! (I would imagine it will have not changed at all!) (我想它根本不会改变!)

What's wrong?怎么了?

I use this for doing what you want:我用它来做你想做的事:

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);
}

This function works as expected and here a variation for sprites.此功能按预期工作,这里是精灵的变体。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM