Javascript 如何使用画布上的图像进行命中测试?
我以这种方式创建图像:Javascript 如何使用画布上的图像进行命中测试?,javascript,canvas,mouseevent,hittest,Javascript,Canvas,Mouseevent,Hittest,我以这种方式创建图像: 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,
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上方移动
我需要这样的东西,但没有任何框架(jquery除外)HitTesting可以通过检查画布上当前位置的内容来完成,可以在画布上单击鼠标或移动事件时调用(这是hit testing的基础)。这可以通过知道放置了什么来实现,比如可以保存图像的边界,当用户单击某个位置或将鼠标移到画布上时,可以检查它是在图像边界之内还是之外。数组或列表可用于此操作
这是如何做到的你不能。画布与
unit245
或角色
对象没有相似之处。实际上,您必须手动检查坐标,并查看它们是否在角色的边界内
例如(假设您的画布是一个名为Canvas的var):
没有内置的方式。我已经写了一些教程来帮助人们开始做这类事情
简言之,您需要记住您绘制的内容和位置,然后检查每次鼠标单击以查看您是否单击了某些内容。画布上的鼠标坐标已经得到回答:
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;
}
};
}
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;
}
};
}