ujs/src/js/objects.js

103 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-04-06 18:46:01 +03:00
class Object {
2023-04-06 16:52:57 +03:00
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
2023-04-23 17:01:17 +03:00
this.ticker = null;
2023-04-06 16:52:57 +03:00
}
}
2023-04-06 18:46:01 +03:00
export class Rect extends Object {
2023-04-06 16:52:57 +03:00
constructor(x, y, w, h, fillColor = 'white') {
super(x, y, w, h);
this.fillColor = fillColor;
}
2023-04-23 18:50:36 +03:00
draw(context, debug = false) {
context.fillStyle = this.fillColor;
context.fillRect(this.x, this.y, this.width, this.height);
if (debug) {
drawDebug(context, this.x, this.y, this.width, this.height);
}
}
2023-04-06 16:52:57 +03:00
}
2023-04-06 18:46:01 +03:00
export class StrokeRect extends Rect {
2023-04-06 16:52:57 +03:00
constructor(x, y, w, h, fillColor = 'white', strokeColor = 'black', strokeWidth = 1) {
super(x, y, w, h, fillColor);
this.strokeWidth = strokeWidth;
this.strokeColor = strokeColor;
}
2023-04-23 18:50:36 +03:00
draw(context, debug = false) {
context.fillStyle = this.fillColor;
context.fillRect(this.x, this.y, this.width, this.height);
context.lineWidth = this.strokeWidth;
context.strokeStyle = this.strokeColor;
context.strokeRect(this.x, this.y, this.width, this.height);
if (debug) {
drawDebug(context, this.x, this.y, this.width, this.height);
}
}
}
export class Sprite {
#loaded;
#image;
constructor(src = null, x, y) {
this.x = x;
this.y = y;
this.width = null;
this.height = null;
this.src = src;
this.loaded = false;
this.#image = new Image();
this.#image.onload = this.#onload();
this.#image.src = this.src;
}
#onload() {
this.width = this.#image.width;
this.height = this.#image.height;
this.loaded = true;
}
image() {
return this.#image;
}
draw(context, debug = false) {
if (this.loaded != true) {
return -1;
}
context.drawImage(this.image(), this.x, this.y);
if (debug) {
drawDebug(context, this.x, this.y, this.#image.width, this.#image.height);
}
}
}
function drawDebug(context, x, y, w, h) {
context.font = '14px serif';
context.fillStyle = '#ffffff';
context.fillText(`${x}x${y}`, x + 1, y - 2);
context.fillStyle = '#000000';
context.fillText(`${x}x${y}`, x, y - 3);
context.lineWidth = 1;
context.strokeStyle = 'blue';
context.strokeRect(x, y, w, h);
2023-04-06 16:52:57 +03:00
}