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

71 lines
2.1 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
{
constructor(tileset, index = 0)
{
this.tileset = tileset;
this.index = index;
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) => {
console.log(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';
}
getElement()
{
return this.htmlElement;
}
}