0

I'm building a simple game engine in javascript, and I'm currently building separate spritesheets for left and right animations, but that seems a bit of a pain... What I want to do is something like this:

function loadSprite(graphic)
{    
   var left_graphic = graphic;
   var right_graphic = graphic.flip();  //Create a flipped copy of the graphic
}

// [...]

function update()
{
   if(speed>0) context.drawImage(left_graphic);
   if(speed<0) context.drawImage(right_graphic);
}

To clarify, I want to create a copy of an Image() object, and mirror flip all it's pixels, so I don't have to maintain two spritesheets.

Is it possible?

Loupax
  • 4,728
  • 6
  • 41
  • 68

1 Answers1

0

First off, you can copy the pixel data using the method described here: Get image data in JavaScript?

I assume you're using a sprite sheet with fixed-sized images. Then you'll have to write an algorithm to flip each image in your image sheet:

for each image in the sheet:
  calculate sheet offset (xOffset, yOffset)
  for each pixel in half the image:
    read pixel ((x, y) + (xOffset, yOffset))
    read opposite pixel ((width - x, y) + (xOffset, yOffset))
    write on top of opposite pixel
    write opposite pixel on top of current pixel
Community
  • 1
  • 1
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • Wow, I didn't think of creating temporary canvas to get the imageData from! This will probably do the trick! Thanks :) – Loupax Dec 11 '11 at 20:28