HTML画布。只有一半的图片被翻转

时间:2016-07-27 13:28:19

标签: javascript html5 canvas

我一直试图在画布上翻转图像。我会翻过来的 整个背景,但这会把所有东西都倒退,我只是申请 这是一些图像。

有问题的图像是画布的全尺寸 WIDTHHEIGHT来自。{/ p>

此功能的图像翻转部分在此处。基本上是形象 绘制到屏幕外画布(_buffer_ctx)然后我使用drawImage 将它添加到最终场景。

// Load images and draw to _buffer_ctx
// ...

let img = this._buffer_ctx.getImageData( 0, 0, WIDTH, HEIGHT );

const IMG_WIDTH  = img.width;
const IMG_HEIGHT = img.height;
const SCAN_WIDTH = IMG_WIDTH / 2;

let out = this._buffer_ctx.createImageData( IMG_WIDTH, IMG_HEIGHT );

const ELEMENTS_PER_PIXEL = 4;

for ( let y = 0; y < IMG_HEIGHT; ++y )
{
  for ( let x = 0; x < SCAN_WIDTH; ++x )
  {
    let p_near = (               x   + y * SCAN_WIDTH ) * ELEMENTS_PER_PIXEL;
    let p_far  = ( ( IMG_WIDTH - x ) + y * SCAN_WIDTH ) * ELEMENTS_PER_PIXEL;

    for ( let e = 0; e < ELEMENTS_PER_PIXEL; ++e )
      out.data[ p_far + e ] = img.data[ p_near + e ];
  }
}

this._buffer_ctx.putImageData( out, 0, 0 );

// Use main_ctx.drawImage( _buffer_ctx, ... )
// ...

我遇到的问题是只有图像的上半部分被翻转。

以下是一些展示我的意思的图片:

Front of the door Back of the door

更新

我注意到只有一半的图像被翻转,所以我尝试将高度乘以2。这让我得到了理想的结果。

const IMG_HEIGHT = img.height * 2; // Just this line.

这对我来说很奇怪,因为getImageData功能和屏幕外画布都使用未加倍的高度。屏外画布使用document.createElement创建,其widthheight属性设置为与屏幕上相同的值。 WIDTHHEIGHT常量也从同一个地方获取它们的值。

我起初认为这是因为画布缩小了图像,但宽度也发生了变化,然而这种作用无法实现,所以我很难理解为什么我只需要乘以高度值。< / p>

1 个答案:

答案 0 :(得分:1)

经过一番混乱之后,看起来@AgataB是正确的。我使用SCAN_WIDTH来查找像素索引的y组件。

代码还存在其他一些问题。

这是固定版本。

let img = this._buffer_ctx.getImageData( 0, 0, WIDTH, HEIGHT );
let out = this._buffer_ctx.createImageData( img );

const IMG_WIDTH  = img.width;
const IMG_HEIGHT = img.height; // Don't need to multiply by two.
const SCAN_WIDTH = IMG_WIDTH  / 2;

const ELEMENTS_PER_PIXEL = 4;

for ( let y = 0; y < IMG_HEIGHT; ++y )
{
  let y_part = y * IMG_WIDTH;
  // Use IMG_WIDTH instead of SCAN_WIDTH so that we get the correct
  // y component. - @AgataB's comment.

  for ( let x = 0; x < SCAN_WIDTH; ++x )
  {
    let x_near = x;
    let x_far  = ( IMG_WIDTH - ( x + 1 ) ); 
    // When calculating the x component of the far pixel index we
    // should add 1 to x. The array is 0 based.

    let p_near = ( x_near + y_part ) * ELEMENTS_PER_PIXEL;
    let p_far  = ( x_far  + y_part ) * ELEMENTS_PER_PIXEL;

    for ( let e = 0; e < ELEMENTS_PER_PIXEL; ++e )
    {
      let near = p_near + e;
      let far  = p_far  + e;

      out.data[ far  ] = img.data[ near ];
      out.data[ near ] = img.data[ far  ];

      // Make sure that we set the left pixels of the output
      // image. This was why only half the image was being drawn
      // when I tried what @AgataB said.
    }
  }