70 lines
1.8 KiB
JavaScript
70 lines
1.8 KiB
JavaScript
import { boardToPic, scaleToTargetSize } from "./picture.js";
|
|
|
|
class Renderer {
|
|
constructor() {
|
|
this.canvas = null;
|
|
this.workCanvas = null;
|
|
this.workCtx = null;
|
|
this.width = null;
|
|
this.height = null;
|
|
this.ctx = null;
|
|
this.refreshRate = 300;
|
|
this.prevFrame = null;
|
|
}
|
|
|
|
// draws the board representation on the canvas
|
|
render(board) {
|
|
const d = board.cellProperties.size;
|
|
// bool to RGBA colors
|
|
const img = boardToPic(board, this.prevFrame);
|
|
this.ctx.clearRect(0, 0, this.width, this.height);
|
|
scaleAndApply(this.ctx, d, () => {
|
|
this.workCtx.putImageData(img, 0, 0);
|
|
this.ctx.drawImage(this.workCanvas, 0, 0, this.width, this.height);
|
|
});
|
|
this.prevFrame = this.workCtx.getImageData(0, 0, board.width, board.height);
|
|
}
|
|
|
|
// draw image on canvas
|
|
renderImage(image, ctx, tw, th) {
|
|
ctx.fillStyle = "black";
|
|
ctx.fillRect(0, 0, tw, th);
|
|
const dimensions = scaleToTargetSize(image.width, image.height, tw, th);
|
|
ctx.drawImage(
|
|
image,
|
|
Math.floor((tw - dimensions[0]) / 2),
|
|
Math.floor((th - dimensions[1]) / 2),
|
|
dimensions[0],
|
|
dimensions[1]
|
|
);
|
|
return ctx.getImageData(0, 0, tw, th);
|
|
}
|
|
|
|
// resize canvas and workcavas
|
|
resize(width, height) {
|
|
this.width = width;
|
|
this.height = height;
|
|
this.canvas.height = height;
|
|
this.canvas.width = width;
|
|
this.workCanvas.height = height;
|
|
this.workCanvas.width = width;
|
|
}
|
|
|
|
// clear any drawing from canvas
|
|
reset() {
|
|
this.ctx.clearRect(0, 0, this.width, this.height);
|
|
}
|
|
}
|
|
|
|
function scaleAndApply(context, ratio, callback) {
|
|
context.save();
|
|
// rescale
|
|
context.imageSmoothingEnabled = false;
|
|
context.scale(ratio, ratio);
|
|
// apply
|
|
callback();
|
|
context.restore();
|
|
}
|
|
|
|
export { Renderer };
|