81 lines
1.7 KiB
JavaScript
81 lines
1.7 KiB
JavaScript
import {getColor, noop} from './utils.js';
|
|
|
|
export default class Sketch {
|
|
constructor (settings) {
|
|
this.lastNow = null;
|
|
|
|
[
|
|
'getContext',
|
|
'getSize',
|
|
'onResize',
|
|
'render',
|
|
].map(method => this[method] = this[method].bind(this));
|
|
|
|
this.draw = settings.draw || noop;
|
|
this.resize = settings.resize || noop;
|
|
this.drawDelay = settings.drawDelay || 50;
|
|
this.container = settings.element || document.body;
|
|
|
|
window.addEventListener('resize', this.onResize);
|
|
|
|
this.canvas = document.createElement('canvas');
|
|
this.canvas.width = this.container.offsetWidth;
|
|
this.canvas.height = this.container.offsetHeight;
|
|
|
|
this.context = this.canvas.getContext('2d');
|
|
|
|
this.container.appendChild(this.canvas);
|
|
|
|
requestAnimationFrame(this.render);
|
|
}
|
|
|
|
getContext () {
|
|
return this.context;
|
|
}
|
|
|
|
getSize () {
|
|
return {
|
|
canvasWidth: this.container.offsetWidth,
|
|
canvasHeight: this.container.offsetHeight,
|
|
}
|
|
}
|
|
|
|
onResize (event) {
|
|
const width = this.container.offsetWidth;
|
|
const height = this.container.offsetHeight;
|
|
|
|
const oldWidth = this.canvas.width;
|
|
const oldHeight = this.canvas.height;
|
|
|
|
const deltaX = width - oldWidth;
|
|
const deltaY = height - oldHeight;
|
|
|
|
this.canvas.width = width;
|
|
this.canvas.height = height;
|
|
|
|
Object.assign(event, {
|
|
height, width,
|
|
oldHeight, oldWidth,
|
|
deltaX, deltaY,
|
|
});
|
|
|
|
this.resize(event);
|
|
}
|
|
|
|
render (now) {
|
|
this.context.lastUTC = this.context.utc || null;
|
|
this.context.utc = Date.now();
|
|
|
|
this.context.now = now;
|
|
this.context.lastNow = this.lastNow;
|
|
|
|
this.draw(this.context);
|
|
|
|
this.lastNow = now;
|
|
|
|
if (this.drawDelay) setTimeout(() => requestAnimationFrame(this.render), this.drawDelay);
|
|
else requestAnimationFrame(this.render);
|
|
}
|
|
}
|
|
|