totoaussi totoaussi - 5 months ago 29
Javascript Question

HTML5 : getImageData with onmousemove make slow my application in Firefox

I create a little html5 game with canvas.

In the canvas, there are many displayed sprites and one of them move automatically from left to right. The others are statics.

When I move the mouse onto the canvas, I draw all sprites in a temporary canvas and I use getImageData to find the sprite onto which the mouse is over.

But getImageData make slow anormally the moving sprite in Firefox.

So what is the solution to avoid this deceleration ?

Here my code :

function getSelectedObject(array_objects)
{
//Clear the temporary canvas :
tmpcx.clearRect(0, 0, tmpc.width, tmpc.height);

/*Search the right sprite object :*/
for(var i = array_objects.length-1; i >= 0; i--)
{
array_objects[i].draw(tmpcx);

imageData = tmpcx.getImageData(mouse_x, mouse_y, 1, 1);

component = imageData.data;

if(component[3] > 0)
{
//Return the sprite object found :
return array_objects[i];
}

else
{
tmpcx.clearRect(0, 0, tmpc.width, tmpc.height);
}
}

return false;
}


canvas.onmousemove = function(event)
{

selectedObject = getSelectedObject(array_objects);

}

Answer

Not sure how much of a performance gain you'd get with this - no need to clear the temp canvas between sprites .... the pixel is clear until a sprite is painted on it!

I've referenced a function called checkBoundingBoxisOver - not sure if you could write this function, but I can't right now - besides, I don't even know what your array_objects are!!!

I would think it were simple, just need the x, y, width, height of a sprite to do a preliminary check if the sprite could even possibly be under the mouse before doing the expensive draw

function getSelectedObject(array_objects) {
    //Clear the temporary canvas :
    tmpcx.clearRect(0, 0, tmpc.width, tmpc.height);
    var sprite;
    /*Search the right sprite object :*/
    for (var i = array_objects.length - 1; i >= 0; i--) {

        sprite = array_objects[i];

        if (checkBoundingBoxisOver(sprite, mouse_x, mouse_y)) {

            sprite.draw(tmpcx);
            imageData = tmpcx.getImageData(mouse_x, mouse_y, 1, 1);
            component = imageData.data;
            if (component[3] > 0) {
                return sprite;
            }
        }
    }
    return false;
}
Comments