DEV Community

Sarah Harrington
Sarah Harrington

Posted on

Canvas Playground: broadcasting & pens

One thing I struggle with when learning something new is feeling like I don't have progress to show. Today I've spent time looking at DynamoDB and EC2 so I can start determining how I want to deploy the server and potentially store the drawing actions but that would leave me without a visible progression.

Pens

To do something on that front, I decided to tackle making it possible to change color schemes for the pens and fixed a bug where the pen color was getting stuck.

Image description

The first step was moving the pens in to their own component.

Pen.tsx

interface PenProps {
  color: {
    value: string;
    name: string;
  }
  changeColor: MouseEventHandler;
}

export default function Pen({ color }: PenProps) {
  return (
    <button 
      className='paint-button' 
      value={color.value} 
      onClick={changeColor}
    >
      <span 
        className='material-symbols-outlined' 
        style={{color: `${color.value}`}}
      >
        brush
      </span>
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode

This component is receiving the pen color object and the changeColor function from the parent.

I wanted to make it so once the pen was selected it would maintain a class on :active. To do that, I passed in the currently selected color and updated the class on the pen to include the class selected if the pen color value and the activeColor matched.

interface PenProps {
  color: {
    value: string;
    name: string;
  },
  activeColor: string;
  changeColor: MouseEventHandler;
}

export default function Pen({ color, activeColor, changeColor }: PenProps) {
  return (
    <button 
      className={`paint-button ${activeColor === color.value ? 'selected' : ''}`} 
      value={color.value} 
      onClick={changeColor}
    >
      <span 
        className='material-symbols-outlined' 
        style={{color: `${color.value}`}}>
          brush
      </span>
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode

Broadcasting

When I was setting up the server, I was sending back out the drawing events from the server, I just did a generic emit on the server so it would send the event back to all connected sockets. That worked, but I don't need the original socket sending info to get it back. To do this, I updated the server to use the broadcast flag after it receives the userIsDrawing event to broadcast that back out to the other attached sockets.

original:

  socket.on('userIsDrawing', (e) => {
    io.emit('userDrawing', e)
  })
Enter fullscreen mode Exit fullscreen mode

broadcasting:

  socket.on('userIsDrawing', (e) => {
    socket.broadcast.emit('userDrawing', e)
  })
Enter fullscreen mode Exit fullscreen mode

Tiny changes felt like some nice progress today:

Image description

Top comments (0)