我有一个画布,我从某些瓷砖(新的Image())绘制,让我说在我的画布上有10x10瓷砖。
每个磁贴都有自己的数据我希望每次用户使用鼠标悬停在磁贴上时都会显示“popup”,其中包含有关此磁贴的信息,它应该跟随鼠标,直到用户离开磁贴。
我想要实现的目标是google maps,但是当我将鼠标移到tile上时它应该跟随鼠标: https://i.gyazo.com/d32cd5869ae9b2e0d9a7053729e2d2aa.mp4
答案 0 :(得分:0)
你需要做三件事:
以上是以上几点的实现:
var GridOverlay = /** @class */ (function () {
/**
* Creates an instance of GridOverlay.
* @param {string} imageSrc
* @param {{
* position: IPoint,
* size: IPoint,
* message: string
* }[]} [zones=[]]
* @memberof GridOverlay
*/
function GridOverlay(imageSrc, zones) {
if (zones === void 0) { zones = []; }
var _this = this;
this.zones = zones;
/**
* The last registered position of the cursor
*
* @type {{ x: number, y: number }}
* @memberof GridOverlay
*/
this.mousePosition = { x: 0, y: 0 };
//Create an image element
this.img = document.createElement("img");
//Create a canvas element
this.canvas = document.createElement("canvas");
//When the image is loaded
this.img.onload = function () {
//Scale canvas to image
_this.canvas.width = _this.img.naturalWidth;
_this.canvas.height = _this.img.naturalHeight;
//Draw on canvas
_this.draw();
};
//Set the "src" attribute to begin loading
this.img.src = imageSrc;
//Listen for "mousemove" on our canvas
this.canvas.onmousemove = this.mouseMove.bind(this);
}
/**
* Registers the current position of the cursor over the canvas, saves the coordinates and calls "draw"
*
* @param {MouseEvent} evt
* @memberof GridOverlay
*/
GridOverlay.prototype.mouseMove = function (evt) {
this.mousePosition.x = evt.offsetX;
this.mousePosition.y = evt.offsetY;
this.draw();
};
/**
* Clears and redraws the canvas with the latest data
*
* @memberof GridOverlay
*/
GridOverlay.prototype.draw = function () {
//Get drawing context
var ctx = this.canvas.getContext("2d");
//Clear canvas
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
//Draw background
ctx.drawImage(this.img, 0, 0);
//Loop through zones
for (var zoneIndex = 0; zoneIndex < this.zones.length; zoneIndex++) {
var zone = this.zones[zoneIndex];
//Check for cursor in zone
if (zone.position.x <= this.mousePosition.x &&
zone.position.x + zone.size.x >= this.mousePosition.x &&
zone.position.y <= this.mousePosition.y &&
zone.position.y + zone.size.y >= this.mousePosition.y) {
//Display zone message on cursor position
ctx.fillText(zone.message, this.mousePosition.x, this.mousePosition.y);
//Break so that we only show a single message
break;
}
}
return this;
};
return GridOverlay;
}());
//TEST
var grid = new GridOverlay("https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=500&h=500", [
{ message: "Zone 1", position: { x: 10, y: 10 }, size: { x: 100, y: 100 } },
{ message: "Zone 2", position: { x: 80, y: 80 }, size: { x: 100, y: 100 } },
]);
document.body.appendChild(grid.canvas);
&#13;