mr-crocs-adventures/tilorswift/js/Field.js

82 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-01-30 20:51:29 +01:00
import TilorswiftFieldClickedEvent from "./events/TilorswiftFieldClickedEvent.js";
import TilorswiftFieldEnteredEvent from "./events/TilorswiftFieldEnteredEvent.js";
2020-01-29 00:21:53 +01:00
export default class Field
{
2020-02-05 22:29:09 +01:00
constructor(tileset, index = -1)
2020-01-29 00:21:53 +01:00
{
this.tileset = tileset;
this.index = index;
2020-02-04 23:03:33 +01:00
this.isEntrancePoint = false;
this.initHtml();
this.initEventListeners();
2020-01-29 00:21:53 +01:00
}
initEventListeners()
2020-01-29 00:21:53 +01:00
{
2020-01-30 20:51:29 +01:00
this.htmlElement.addEventListener(
'mousedown', (event) => {
window.dispatchEvent(new TilorswiftFieldClickedEvent(this, event.button));
}
);
this.htmlElement.addEventListener(
'contextmenu', (event) => {
window.dispatchEvent(new TilorswiftFieldClickedEvent(this), event.button);
2020-01-30 20:51:29 +01:00
}
);
this.htmlElement.addEventListener(
'mouseenter', () => {
window.dispatchEvent(new TilorswiftFieldEnteredEvent(this));
}
);
}
2020-01-30 20:51:29 +01:00
initHtml()
{
this.htmlElement = document.createElement('td');
this.className = 'field';
this.setupElement();
this.addSelector();
}
setupElement()
{
2020-01-29 00:21:53 +01:00
this.htmlElement.classList.add(this.className);
this.htmlElement.style.width = String(this.tileset.getTileWidth()) + 'px';
this.htmlElement.style.height = String(this.tileset.getTileHeight()) + 'px';
this.htmlElement.style.backgroundSize = 'auto ' + this.tileset.getTileHeight() + 'px';
this.htmlElement.style.backgroundImage = 'url("' + this.tileset.image.src + '")';
this.htmlElement.style.backgroundPositionX = -this.index * this.tileset.getTileWidth() + 'px';
}
2020-01-30 20:51:29 +01:00
addSelector()
{
2020-01-30 20:51:29 +01:00
let hoverElement = document.createElement('div');
hoverElement.classList.add('selection');
this.htmlElement.appendChild(hoverElement);
2020-01-29 00:21:53 +01:00
}
setIndex(index)
{
this.index = index;
this.htmlElement.style.backgroundPositionX = -this.index * this.tileset.getTileWidth() + 'px';
}
2020-02-04 23:03:33 +01:00
setEntrancePoint(bool)
{
this.isEntrancePoint = bool;
if (this.isEntrancePoint) {
this.htmlElement.classList.add('entrance');
} else {
this.htmlElement.classList.remove('entrance');
}
}
2020-01-29 00:21:53 +01:00
getElement()
{
return this.htmlElement;
}
}