-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathShader.js
103 lines (83 loc) · 2.1 KB
/
Shader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Base class for shaders.
* Any class that extends the shader should
* implement it's own render or renderPixel method,
* and has the ability to implement it's own prepare
* or finish methods to perform actions before
* and after rendering pixels
*/
export default class Shader {
constructor (name) {
this.name = name
this.options = {}
this.horizontalSkip = 1
this.verticalSkip = 1
}
configure (options) {
this.options = options
}
reset () {
this.options = {}
}
shouldFill () {
return this.options.fill || this.options.fill === undefined
}
shouldStroke () {
return this.options.stroke || this.options.stroke === undefined
}
prepare (ctx, data, palette) {
ctx.lineWidth = 1
if (palette.backgroundColor) {
ctx.fillStyle = palette.backgroundColor
ctx.fillRect(0, 0,
data.blockDimension * data.columnCount * this.horizontalSkip,
data.blockDimension * data.rowCount * this.verticalSkip)
}
}
render (ctx, data, palette) {
this.prepare(ctx, data, palette)
this.renderPixels(ctx, data, palette)
this.finish(ctx, data, palette)
}
renderPixels (ctx, data, palette) {
for (let ri=0; ri < data.rowCount; ri ++) {
for (let ci=0; ci < data.columnCount; ci ++) {
this.renderPixel(ctx, data.pixelGrid[ci][ri], data, palette)
}
}
}
finish (ctx, data, palette) {
// no op
}
fill (ctx) {
if (this.shouldFill()) {
ctx.fill()
}
}
stroke (ctx) {
if (!this.shouldFill()) {
ctx.lineWidth = Math.max(2, Math.floor(this.options.blockDimension/25))
} else {
ctx.lineWidth = 1
}
if (this.shouldStroke()) {
ctx.stroke()
}
}
renderPixel (ctx, pixel, data, palette) {
// no op
}
fillPixelWithPalette(ctx, pixel, palette) {
this.fillPixelWithColor(
ctx,
palette.getColorFromPixel(pixel),
palette.getBorderColorFromPixel(pixel)
)
}
fillPixelWithColor(ctx, fillColor, borderColor) {
ctx.fillStyle = fillColor
ctx.strokeStyle = borderColor
this.fill(ctx)
this.stroke(ctx)
}
}