Subscribe to get access to this video

and the whole library of videos, sample code, and tutorials.

Drawing Pixels from the Blockchain

We have PixelChanged events coming over Websockets and we need to draw them on our canvas.

What we need to do is capture each event, parse the color string, and then write the pixel to the canvas.

Let’s take each step at a time.

First, take a look at the event that comes through. The x, y, and color are all strings. We want them all to be integers.

Actually, x and y are plain integers and we need to parse color into three integers: R G B, each one being between 0 and 255.

Let’s write a function that, given an event, will parse these values and write the pixel.

// * We haven't written `writePixel` yet, but we well
// * We also need to write parseColor

function writePixelWithEvent(event) {
  let { x, y, color } = event.returnValues;
  writePixel(
    parseInt(x),
    parseInt(y),
    parseColor(color)
  );
}

parseColor will take this raw color string, split the bytes, and convert it to a three-element array: each element corresponding to a channel red, green, blue. You don’t need to worry too much about how this function works. Just know that it returns a three-element array.

function parseColor(rawColor) {
  let rgb = [];
  for (let i = 0; i < rawColor.length; i += 2) {
    let chunk = rawColor.substring(i, i + 2);
    if (chunk !== '0x') {
      rgb.push(parseInt(chunk, 16).toString(10));
    }
  }
  return rgb;
}

Now we need to write this particular pixel. What we’re going to do is read the current image data, find the index for this pixel, and update its color.

 

Subscribe to get the full text of this lesson

and the entire library of videos, sample code, and tutorials.