Search code examples
javascripthtmlhtml5-canvaskineticjs

HTML 5 Canvas Cards Game


I am making a real time cards game in HTML 5 canvas. The backend server is node.js. Designing the cards table is giving me a hard time, because I just don't want to draw everything on canvas.

This is something I want to achieve for the cards table. enter image description here

One option I have right now is to make this image as the background of the canvas and animate my cards over it. This is good for performance point of view, but then I may not be able to capture events like cards moved in a particular area.

What is the best way to solve this situation? Should I set it as background of canvas, or create it over canvas with css?

FYI: I am using kineticjs as a front-end framework for developing this game.


Solution

  • You can determine which cell the mouse is over like this:

    • Listen for dragmove events which fire when the card is being dragged.

    • Inside the dragmove handler, get the mouse position,

    • Mathematically calculate which cell the mouse is over

    A Demo: http://jsfiddle.net/m1erickson/DN5hA/

    Here's how it might look in code:

    card1.on("dragmove",function(){
        var mouse=stage.getPointerPosition();
        var cellX=parseInt((mouse.x-borderOffsetX)/cellWidth);
        var cellY=parseInt((mouse.y-borderOffsetY)/cellHeight);
        highlight.position({
            x:borderOffsetX+cellX*cellWidth,
            y:borderOffsetY+cellY*cellHeight
        });
        layer.draw();
    });
    
    
    });