Canvas Pixel Test
by MegaScience
HTML
<canvas id="myCanvas" width="450" height="450">
Your browser does not support the canvas element.
</canvas>
CSS
html,
body {
height: 100%;
margin: 0;
}
body {
background-color: violet;
display: flex;
justify-content: center;
align-items: center;
}
canvas {
border: 10px ridge brown;
}
JavaScript
const drawData = {
e: {},
s: {
pixelScale: 38,
},
init: function() {
this.e.canvas = document.getElementById("myCanvas");
this.e.ctx = this.e.canvas.getContext("2d");
this.scaleCanvasToMap(logoData, "width");
this.debug();
this.drawMap(logoData);
},
scaleCanvasToMap: function(map, reflect) {
for (const [index, dim] of["width", "height"].entries()) {
let minValue = map.reduce((max, arr) => Math.max(max, arr[index]), Number.NEGATIVE_INFINITY);
if (reflect === dim) minValue *= 2;
//minValue += 2;
this.s[dim] = ++minValue;
this.e.canvas[dim] = minValue * this.s.pixelScale;
}
},
correctCanvas: function() {
//["width", "height"].forEach(sca => this.e.canvas[sca] -= this.e.canvas[sca] % this.s.pixelScale);
for (const dim of["width", "height"]) this.e.canvas[dim] -= this.e.canvas[dim] % this.s.pixelScale;
},
drawMap: function(map) {
//logoData.forEach(coord => this.reflectPixel.apply(this, coord));
for (const coord of map) this.reflectPixel.apply(this, coord);
},
drawPixel: function(x, y, c) {
this.e.ctx.fillStyle = c || "#0099FF";
this.e.ctx.fillRect(x * this.s.pixelScale, y * this.s.pixelScale, this.s.pixelScale, this.s.pixelScale);
},
reflectPixel: function(x, y, c, a) {
//x++, y++;
this.drawPixel(x, y, c);
switch (a) {
case "y":
this.drawPixel(x, this.s.height - y - 1, c);
break;
case "x":
default:
this.drawPixel(this.s.width - x - 1, y, c);
}
},
debug: function() {
const colors = ["red", "orange", "yellow", "lime", "aqua", "blue", "fuchsia"]
for (let x = 0; x < this.s.width / 2; x++) {
for (let y = 0; y < this.s.height; y++) {
const index = y * Math.floor(this.s.height) + x;
const color = colors[index % colors.length];
this.reflectPixel(x, y, color, "x");
}
}
}
};
const logoData = [
[0, 2],
[0, 3],
[0, 4],
[1, 4],
[1, 5],
[1, 6],
...