0

I have a custom map as an image which I am loading in a html5 canvas. Here is sample image:

[![Sample image][1]][1]

I am looking to fill the background color of any room from this image based on some logic from javascript. I have another application from where I can get the x-axis and y-axis of a room(center of each room as position in px). Now what I am interested in is to fill a white background of room with some color from javascript same as we do in paintbursh(mac application). Here is what I am interesting in result: [![enter image description here][2]][2]

Can someone tell me is it possible using html canvas and how I can fill the certain part of a image in canvas from javascript.

  • It's possible, but you need to know the limits of the shape. If you are constructing that image with canvas, when you begin the path you can set the background color and it will be rendered as this. – Marcos Pérez Gude May 18 '16 at 10:55
  • Well this is a image constructed by third party so have no idea about the limits of a room. But do i really care of the limits why not we just replace the white px into some color same as paintbursh application? –  May 18 '16 at 11:02
  • You can paint all white pixels to another color, the problem is that if you don't know the limits, all white pixels will be changed, including outside that room. That's why you need the limits. You can detect the black borders too, but the calculations to achieve it will be hard to develop and slow performance for the browser. – Marcos Pérez Gude May 18 '16 at 11:06
  • 1
    *if* the borders of the rooms are always limited by a shape (=closed), yo can use a flood fill algorithm. Mind that you need to access the raw (pixel) data of the image, so it should be hosted on same site to avoid cross origin conflict and `black` canvas. I made once a small demo of flood fill here if interested : https://jsfiddle.net/gamealchemist/gTa4r/ – GameAlchemist May 18 '16 at 11:12
  • @GameAlchemist I try to load image into example which you shared with me. I change in drawSomething() and load image in canvas but it seem to be not working with images or may be i am doing something wrong. Can you please tell me where is a problem. https://jsfiddle.net/mnomansadiq/gTa4r/6/ –  May 18 '16 at 12:58
  • My bad forgot to add imageObj.crossOrigin = "Anonymous"; when loading image. It is now working as expected. Thanks a lot –  May 18 '16 at 13:47
  • @GameAlchemist I found something strange with this code, If we click twice on the same circle then it crashing the browser. How we can avoid that if a shape is already fill it will reset it back and then refill again OR any other work around to avoid this problem ? –  May 20 '16 at 09:09
  • @user526206 : Oh my bad, i just made this work to understand how it works without really testing. It should be ok now. – GameAlchemist May 20 '16 at 11:22

0 Answers0