tempera-frontend/app.ts

60 lines
1.6 KiB
TypeScript

class Point {
x: number;
y: number;
style: string;
constructor(x: number, y: number, style: string) {
this.x = x;
this.y = y;
this.style = style;
}
}
class Stroke {
vertices: Array<Point>;
constructor(vertices: Array<Point>) {
this.vertices = vertices;
}
draw(ctx: CanvasRenderingContext2D) {
var path = new Path2D();
path.moveTo(this.vertices[0].x, this.vertices[0].y);
for(var i = 1; i < this.vertices.length; i++) {
ctx.strokeStyle = this.vertices[i].style;
path.lineTo(this.vertices[i].x, this.vertices[i].y);
ctx.stroke(path);
}
}
}
class CanvasState {
}
window.onload = () => {
var canvas = document.getElementById("draw-area") as HTMLCanvasElement;
if(!canvas.getContext) {
alert("HTML Canvas not supported! Application will not run");
throw new Error("HTML Canvas not supported!");
}
var ctx = canvas.getContext("2d");
var lastPoint: Point | null = null;
var points: Array<Point> = [];
var box = canvas.getBoundingClientRect();
var addPointsToArray = false;
canvas.addEventListener('mousemove', (ev: MouseEvent) => {
if(addPointsToArray) {
var point = new Point(ev.clientX - box.x, ev.clientY - box.y, `rgb(${Math.round(Math.random()*255)},${Math.round(Math.random()*255)},${Math.round(Math.random()*255)})`)
if(lastPoint != null) {
new Stroke([lastPoint, point]).draw(ctx);
}
lastPoint = point;
points.push(point);
}
});
canvas.addEventListener('mousedown', (ev: MouseEvent) => {
addPointsToArray = true;
});
canvas.addEventListener('mouseup', (ev: MouseEvent) => {
addPointsToArray = false;
lastPoint = null;
points = [];
});
};