6.2
HTML
<canvas id="myCanvas" width="1000" height="1000">
Your browser does not support the HTML5 canvas tag.
</canvas>
JavaScript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 1000, 1000);
var lines = getData();
for (i = 0; i <= lines.length; i++) {
(function(i) {
window.setTimeout(function() {
var line = lines[i];
console.log(line);
if (line != null) {
var m = line.match(/\d+,\d+/g);
leftTop = m[0].split(',');
rightBottom = m[1].split(',');
if (line[6] == 'n')
turnOn(ctx, leftTop[0], leftTop[1], rightBottom[0], rightBottom[1]);
if (line[6] == 'f')
turnOff(ctx, leftTop[0], leftTop[1], rightBottom[0], rightBottom[1]);
if (line[6] == ' ')
toggle(ctx, leftTop[0], leftTop[1], rightBottom[0], rightBottom[1]);
}
if (i == 300)
count();
}, i * 10);
}(i));
}
function count() {
count = 0;
var total = ctx.getImageData(0, 0, 1000, 1000);
for (var i = 0; i <= total.data.length; i += 4) {
var brightness = total.data[i + 1];
if (brightness != null)
count = count + brightness;
}
alert(`The total brightness is ${count}`);
}
function turnOn(ctx, l, t, r, b) {
console.log(`Turning on ${l},${t} through ${r},${b}`);
var rect = ctx.getImageData(l, t, r - l + 1, b - t + 1);
for (var i = 0; i <= rect.data.length; i += 4) {
rect.data[i + 1]++;
}
ctx.putImageData(rect, l, t);
}
function turnOff(ctx, l, t, r, b) {
console.log(`Turning off ${l},${t} through ${r},${b}`);
var rect = ctx.getImageData(l, t, r - l + 1, b - t + 1);
for (var i = 0; i <= rect.data.length; i += 4) {
rect.data[i + 1]--;
}
ctx.putImageData(rect, l, t);
}
function toggle(ctx, l, t, r, b) {
console.log(`Toggling ${l},${t} through ${r},${b}`);
var rect = ctx.getImageData(l, t, r - l + 1, b - t + 1);
for (var i = 0; i <= rect.data.length; i += 4) {
rect.data[i + 1] += 2;
}
ctx.putImageData(rect, l,...