2

我以这种方式创建图像:

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

我在这样的对象中使用图像:

function Character(hp, image){
    this.hp = hp;
    this.image = image;
};

我多次调用它,例如:

unit245 = new Character(100, orc);

我以这种方式绘制它,例如:

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

如何在画布上单击鼠标或在 unit245 上方移动?

我需要这样的东西http://easeljs.com/examples/dragAndDrop.html但没有任何框架(jquery除外)

4

4 回答 4

3

没有内置的方式。我已经写了一些关于在画布上制作可移动和可选形状的教程,以帮助人们开始使用这种东西。

简而言之,您需要记住您绘制的内容和位置,然后检查每次鼠标单击以查看您是否单击了某些东西。

于 2011-09-29T17:32:28.580 回答
0

HitTesting 可以通过检查画布上当前位置的内容来完成,这可以通过鼠标单击或画布上的移动事件来调用(这是命中测试的基础)。这可以通过了解已放置的内容来完成,例如可以保存图像的边界,并且当用户单击某处或将鼠标移到画布上时,您可以检查它是在图像边界内还是在其外。数组或列表可用于此。

是如何做到的

于 2011-09-29T16:15:45.470 回答
0

你不能。画布与您的对象unit245Character对象没有任何相似之处。您将不得不手动检查坐标,看看它们是否在您为角色设置的范围内。

例如(假设您的 Canvas 是一个名为 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!");
  }
}

在你的情况下:

unit245.x = 15
unit245.y = 55
unit245.width = 100
unit245.height = 100
于 2011-09-29T16:16:48.053 回答
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;
        }  
    };
}
于 2011-11-01T08:11:05.667 回答