Sign in to follow this  
Stephen Persson

Drawing pixel by pixel with BitmapData

Recommended Posts

What's the right way to draw an image pixel by pixel with bitmapdata?

Assuming I'm getting the data from a matrix.

var image = [['rgb(  0,  0,  0)', 'rgb(  0,  0,  0)', 'rgb(255,255,255)', 'rgb(  0,  0,  0)', 'rgb(  0,  0,  0)'],             ['rgb(  0,  0,  0)', 'rgb(  0,  0,  0)', 'rgb(255,255,255)', 'rgb(  0,  0,  0)', 'rgb(  0,  0,  0)'],             ['rgb(  0,  0,  0)', 'rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(  0,  0,  0)'],             ['rgb(  0,  0,  0)', 'rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(  0,  0,  0)'],             ['rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(255,255,255)']];var bmd = game.make.bitmapData(game.width, game.height);for (var x = 0; x < image.length; x++) {  for (var y = 0; y < image[x].length; y++) {    bmd.??????????  }}bmd.addToWorld();

Share this post


Link to post
Share on other sites

BitmapData has a setPixel method, or "setPixel32" if you need alpha values.

It would require you to parse that string, though, since it takes the rgb values separately as numbers.

It works, but I tried on a 640x480 image and it was prohibitively slow until it crashed.

This is what I did:

var image = [[[0, 0, 0], [0, 0, 0], [255, 255, 255], ..., [255, 255, 255], [255, 255, 255], [255, 255, 255]]];var bmd = game.make.bitmapData(game.width, game.height);for (var x = 0; x < image.length; x++) {  for (var y = 0; y < image[x].length; y++) {    bmd.setPixel(x, y, image[y][x][0], image[y][x][1], image[y][x][2]);  }}bmd.addToWorld();

setPixel uses putImageData. Is this ok?

Share this post


Link to post
Share on other sites

If it's prohibitively slow, try setting the immediate flag to "false". By default the flag is "true" and image gets updated every time you set a pixel. I don't really know the inner workings, but accessing and manipulating the canvas 640x480 times is probably a very consuming operation, especially since your intention is probably to only update once you're done.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.