Jump to content

Drawing pixel by pixel with BitmapData


Stephen Persson
 Share

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();
Link to comment
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?

Link to comment
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.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...