es6 syntax learning

This commit is contained in:
Blue 2018-11-18 21:09:30 +03:00
parent 8d215e1db0
commit a463c64b01
4 changed files with 22 additions and 15 deletions

View File

@ -1,18 +1,19 @@
import Color from "./color.js";
class Canvas {
element;
constructor() {
this.element = document.createElement("canvas");
this.element.width = 1000;
this.element.height = 1000;
this._ctx = this.element.getContext("2d");
},
}
setFillColor(color) {
this._ctx.fillStyle = color.rgba();
},
}
resetStyle() {
this._ctx.fillStyle = "";
},
}
draw(shape) {
this._ctx.fillStyle = shape._color.rgba();
shape.draw(this._ctx);

View File

@ -17,7 +17,7 @@ class Color {
this._g = g;
this._b = b;
this._a = a;
},
}
rgba() {
let out = "rgba(";
out += Math.floor(this._r * 255);
@ -30,7 +30,8 @@ class Color {
out += ")";
return out;
},
}
static random() {
return new Color(Math.random(), Math.random(), Math.random(), Math.random());
}

View File

@ -1,13 +1,18 @@
import Shape from "./shape.js";
class Rectangle extends Shape {
className: "Rectangle",
className = "Rectangle";
constructor(x, y, color, width, height) {
super(x, y, color);
this._width = width;
this._height = height;
},
}
draw(context) {
context.fillRect(this._x, this._y, this._x + this._width, this._y + this._height);
}
static randomOptions() {
opts = super.randomOptions();
@ -15,12 +20,9 @@ class Rectangle extends Shape {
opts.height = Math.floor(Math.random() * maxHeight);
return opts;
},
}
static fromOptions(o) {
return new Rectangle(o.x, o.y, o.color, o.width, o.height);
},
draw(context) {
context.fillRect(this._x, this._y, this._x + this._width, this._y + this._height);
}
}

View File

@ -1,22 +1,25 @@
import Color from "./color.js";
class Shape {
className: "Shape",
className = "Shape";
color;
constructor(x, y, color) {
this._x = x;
this._y = y;
this.color = color;
},
}
draw(context) {
throw new Error("A pure virtual method call of a shape " + this.className);
},
}
static randomOptions() {
return {
x: Math.floor(Math.random() * maxX),
y: Math.floor(Math.random() * maxY),
color: Color.random()
}
},
}
static fromOptions(o) {
return new Shape(o.x, o.y, o.color);
}