Question

I would like to make a good performance hit test for png images and other shapes. I don't really care what shapes they are because with this technique there is no performance issues at checking (not setup).

I intent to collect all the images on the screen in a secondary canvas just for hit test. For each image drawn I will create a new color which is attached to that particular image. Then I draw all of them in the canvas, each image will have a different fill color.

When I click on a pixel (x, y) it will get the color (r, g, b). Every color is mapped to a image, so I get the image clicked with no error (I don't waste with finding what was hit with that click).

enter image description here

I know it will be limited to 256*256*256=16 777 216 items because those are all the colors but I don't think it will be a problem for now...

So what I really need is to know how to put those fill colors on the secondary canvas which is based only on the visible pixels for each image.

UPDATE

enter image description here As you can see to the right it's the hit test map. So if I click on the black shade (c) I instantly know I've clicked on the blue box without any other calculation.

One improvement it would be to cache the alpha data. Also reuse the same alpha data for each image instance (we must take care about scaling and rotation...).

thanks

Was it helpful?

Solution

Here’s how you would color-mask the non-transparent pixels of a canvas image.

Be sure you replace "PutYourImageHere.png" with your own image url.

<!doctype html>
<html>
<head>

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid blue;}
</style>

<script>
    $(function(){

        var img=new Image();
        img.onload=function(){

          var red=255;
          var blue=0;
          var green=0;

          var canvasCopy=document.getElementById("canvasCopy");
          var ctxCopy=canvasCopy.getContext("2d");

          var c=document.getElementById("canvas");
          var ctx=c.getContext("2d");
          ctx.drawImage(this,0,0);

          var imgData=ctx.getImageData(0,0,c.width,c.height);

          for (var i=0;i<imgData.data.length;i+=4)
            {
                if(imgData.data[i+3]>0){
                    imgData.data[i]=red;
                    imgData.data[i+1]=green;
                    imgData.data[i+2]=blue;
                    imgData.data[i+3]=255;
                }
            }
          ctxCopy.putImageData(imgData,0,0);
        }
        img.src = "PutYourImageHere.png";

    }); // end $(function(){});
</script>

</head>

<body>

    <canvas id="canvas" width="300" height="300"></canvas>
    <canvas id="canvasCopy" width="300" height="300"></canvas>

</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top