[英]Creating Mouse Event Handlers For Canvas Shapes
我正在使用画布使用javascript编写基于图块的游戏,并且想知道如何在鼠标输入图块尺寸时创建一个简单的事件处理程序。
过去,我曾经使用过jquery的http://api.jquery.com/mousemove/ ,但对于一个非常简单的应用程序,却似乎无法迅速解决这种情况。
嗯..
我开始写这篇文章时却一无所知,但是我只是像上面一样尝试使用jquery mousemove。 我有一个工作版本,但似乎“缓慢”且笨拙。 它似乎不流畅或不准确。
我将所有模式代码放入js小提琴以轻松共享: http : //jsfiddle.net/Robodude/6bS6r/1/
所以发生的是:
1)jQuery的mousemove事件处理程序触发
2)将鼠标对象信息发送到GameBoard
3)将鼠标对象信息发送到地图
4)循环遍历所有图块,并向每个图块发送鼠标对象
5)然后,单个图块确定鼠标坐标是否在其边界内。 (并执行某些操作-在这种情况下,我只是将tile属性更改为白色)
但以下是我最关注的部分。
$("#canvas").mousemove(function (e) {
mouse.X = e.pageX;
mouse.Y = e.pageY;
game.MouseMove(mouse);
Draw();
});
function GameBoard() {
this.Map = new Map();
this.Units = new Units();
this.MouseMove = function (Mouse) {
this.Map.MouseMove(Mouse);
};
}
function Map() {
this.LevelData = Level_1(); // array
this.Level = [];
this.BuildLevel = function () {
var t = new Tile();
for (var i = 0; i < this.LevelData.length; i++) {
this.Level.push([]);
for (var a = 0; a < this.LevelData[i].length; a++) {
var terrain;
if (this.LevelData[i][a] == "w") {
terrain = new Water({ X: a * t.Width, Y: i * t.Height });
}
else if (this.LevelData[i][a] == "g") {
terrain = new Grass({ X: a * t.Width, Y: i * t.Height });
}
this.Level[i].push(terrain);
}
}
};
this.Draw = function () {
for (var i = 0; i < this.Level.length; i++) {
for (var a = 0; a < this.Level[i].length; a++) {
this.Level[i][a].Draw();
}
}
};
this.MouseMove = function (Mouse) {
for (var i = 0; i < this.Level.length; i++) {
for (var a = 0; a < this.Level[i].length; a++) {
this.Level[i][a].MouseMove(Mouse);
}
}
};
this.BuildLevel();
}
function Tile(obj) {
//defaults
var X = 0;
var Y = 0;
var Height = 40;
var Width = 40;
var Image = "Placeholder.png";
var Red = 0;
var Green = 0;
var Blue = 0;
var Opacity = 1;
// ...
this.Draw = function () {
ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
ctx.fillRect(this.X, this.Y, this.Width, this.Height);
};
this.MouseMove = function (Mouse) {
if ((Mouse.X >= this.X) && (Mouse.X <= this.Xmax) && (Mouse.Y >= this.Y) && (Mouse.Y <= this.Ymax)) {
this.Red = 255;
this.Green = 255;
this.Blue = 255;
}
};
}
如果您有一个瓷砖网格,则在给定鼠标位置的情况下,可以将X鼠标位置除以瓷砖的宽度,将Y鼠标位置除以瓷砖的宽度,再将Y位置除以高度和地板,即可检索到瓷砖的X和Y索引。
那将使Map
的MouseMove
:
this.MouseMove = function (Mouse) {
var t = new Tile();
var tileX = Math.floor(mouse.X / t.Width);
var tileY = Math.floor(mouse.Y / t.Height);
this.Level[tileY][tileX].MouseMove(Mouse);
};
编辑:您要求一些一般性的建议。 干得好:
Mouse
是一个简单的结构; 我认为它不需要自己的课程。 也许使用对象文字。 (例如{x: 1, y: 2}
) prototype
对象,而不是对每种方法都使用this.method = function() { ... }
。 这可能会提高性能,因为它只需要创建一次函数,而不必在创建该类的新对象时创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.