2

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 = hp;
    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)

asci
  • 2,540
  • 4
  • 16
  • 15
  • Mouse co-ordinates on canvas has already been answered: http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas – James Sep 29 '11 at 16:13

4 Answers4

3

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.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
0

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

SpeedBirdNine
  • 4,610
  • 11
  • 49
  • 67
0

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
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
0
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;
        }  
    };
}
asci
  • 2,540
  • 4
  • 16
  • 15