mr-crocs-adventures/js/retro/RetroSprite.js

102 lines
2.6 KiB
JavaScript

import GeometryPoint from "../geometry/GeometryPoint.js";
import GeometryRect from "../geometry/GeometryRect.js";
export default class RetroSprite
{
constructor(image, scale = 1)
{
this.image = new Image();
this.image.src = image;
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.position = new GeometryPoint();
this.scale = scale;
this.render();
}
/**
* Returns the position of the sprite's center
*
* @returns {GeometryPoint}
*/
getCenter()
{
this.getRect().getCenter();
}
setFootPosition(x, y)
{
this.position.x = x - this.canvas.width * 0.5;
this.position.y = y - this.canvas.height;
}
getRect()
{
return new GeometryRect(this.position.x, this.position.y, this.canvas.width, this.canvas.height);
}
getWidth()
{
return this.canvas.width;
}
getHeight()
{
return this.canvas.height;
}
getFootHeight()
{
return new GeometryPoint(this.position.x, this.position.y + this.getHeight());
}
getPositionLeftFoot()
{
return new GeometryPoint(this.position.x - this.getWidth() * 0.5, this.position.y);
}
getPositionRightFoot()
{
return new GeometryPoint(this.position.x + this.getWidth() * 0.5, this.position.y);
}
draw(context)
{
context.drawImage(this.canvas, this.position.x, this.position.y);
}
hasRectCollisionWith(sprite)
{
return this.getRect().getRectIntersection(sprite.getRect()) !== null;
}
hasCollisionWith(sprite)
{
}
render()
{
let canvasTemp = document.createElement('canvas');
canvasTemp.width = this.image.width * this.scale;
canvasTemp.height = this.image.height * this.scale;
let contextTemp = canvasTemp.getContext('2d');
contextTemp.drawImage(this.image, 0, 0);
this.canvas.width = this.image.width * this.scale;
this.canvas.height = this.image.height * this.scale;
this.context.clearRect(0, 0, this.image.width * this.scale, this.image.height * this.scale);
for (let y = 0; y < this.image.height; y++) {
for (let x = 0; x < this.image.width; x++) {
let pixel = contextTemp.getImageData(x, y, 1, 1).data;
this.context.globalAlpha = pixel[3] / 255;
this.context.fillStyle = 'rgb(' + pixel[0] + ',' + pixel[1] + ',' + pixel[2] + ')';
this.context.fillRect(x * this.scale, y * this.scale, this.scale, this.scale);
}
}
}
}