开发者

How i can get hit test with image on canvas?

I create image in this way:

var orc = new Image();
        orc.src = "./orc.png";

I use image in objects like this:

function Character(hp, image){
    this.hp = h开发者_如何学Pythonp;
    this.image = image;
};

I call it in several times, like:

unit245 = new Character(100, orc);

And I draw it in this way, for example:

ctx.drawImage(unit245.image, 15, 55, 100, 100);

How I can get mouse click or move above my unit245 on canvas?

I need something like this http://easeljs.com/examples/dragAndDrop.html but without any frameworks (except jquery)


There is no built in way. I've written a few tutorials on making movable and selectable shapes on a Canvas to help people get started with this sort of thing though.

In short you need to remember what you have drawn and where, and then check each mouse click to see if you have clicked on something.


HitTesting can be done by checking what is present at the current location over the canvas, which can be called upon mouse click or move event over the canvas (which is the basis of hit testing). This can be done by knowing what has been placed where, like the bounds of an image can be saved, and when user clicks somewhere or moved the mouse over the canvas, you can check whether it is inside the image bounds or outside it. Array or List can be used for this.

Here is how this can be done


You cannot. The canvas has no semblance of what your unit245 or Character object is. You will have to actually manually check the coordinates and see if they fall within the bounds that you have for the character.

For example (assuming your Canvas is a var named canvas):

canvas.onclick = function(e) {
  if (e.x >= unit245.x && e.x <= unit245.x + unit245.width && e.y >= unit245.y && e.y <= unit245.y + unit245.height) {
    alert("You clicked unit245!");
  }
}

In your case:

unit245.x = 15
unit245.y = 55
unit245.width = 100
unit245.height = 100


function Item(img, x, y){
    this.image = img;
    this.x = x;
    this.y = y;
    this.canv = document.createElement("canvas");
    this.canv.width = this.image.width;
    this.canv.height = this.image.height;
    this.ctx = this.canv.getContext('2d');
    this.ctx.drawImage(this.image, 0, 0, CELL_SIZE, CELL_SIZE);     
    this.hit = function  (mx, my) {
        var clr;
        clr = this.ctx.getImageData(mx - this.x, my - this.y, 1, 1).data;
        if (clr[3] > 250) {
            //On object
            this.image = gold_glow;
        } else {
            //Leave object
            this.image = gold;
        }  
    };
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜