Working Version

This commit is contained in:
Andrew Stephens
2022-12-16 09:27:34 -05:00
commit ee6a9dc1a5
2 changed files with 77 additions and 0 deletions

77
index.html Normal file
View File

@@ -0,0 +1,77 @@
<!DOCTYPE html>
<html>
<style>
.canvasstyle {
width: 90%;
object-fit: contain;
border: 1px solid black;
}
</style>
<script>
function dither(imageData) {
let output = new ImageData(imageData.width, imageData.height)
for (i = 0; i < imageData.data.length; i += 4) {
output.data[i] = output.data[i + 1] = output.data[i + 2] = Math.floor(imageData.data[i] * 0.3 + imageData.data[i + 1] * 0.59 + imageData.data[i + 2] * 0.11)
output.data[i + 3] = imageData.data[i + 3]
}
console.log("grey")
let slidingErrorWindow = [new Float32Array(imageData.width), new Float32Array(imageData.width), new Float32Array(imageData.width)]
const offsets = [[1, 0], [2, 0], [-1, 1], [0, 1], [1, 1], [0, 2]]
for (let y = 0, limY = imageData.height; y < limY; ++y) {
for (let x = 0, limX = imageData.width; x < limX; ++x) {
let i = ((y * limX) + x) * 4;
let accumulatedError = Math.floor(slidingErrorWindow[0][x])
let expectedMono = output.data[i] + accumulatedError
let monoValue = expectedMono
if (monoValue <= 127) {
monoValue = 0
} else {
monoValue = 255
}
let error = (expectedMono - monoValue) / 8.0
for (let q = 0; q < offsets.length; ++q) {
let offsetX = offsets[q][0] + x
let offsetY = offsets[q][1] + y
if ((offsetX >= 0) && (offsetX < slidingErrorWindow[0].length))
slidingErrorWindow[offsets[q][1]][offsetX] += error
}
output.data[i] = output.data[i + 1] = output.data[i + 2] = monoValue
}
// move the sliding window
slidingErrorWindow.push(slidingErrorWindow.shift())
slidingErrorWindow[2].fill(0, 0, slidingErrorWindow[2].length)
}
console.log("done")
return output
}
function setImage(src, target) {
let image = new Image()
image.onload = () => {
let gc = target.getContext("2d")
gc.drawImage(image, 0, 0, target.width, target.height)
let original = gc.getImageData(0, 0, target.width, target.height)
let dithered = dither(original)
gc.putImageData(dithered, 0, 0)
}
image.src = src
}
window.addEventListener("load", (e) => {
setImage("test.jpg", document.getElementById("drawing"))
})
</script>
<body>
<canvas id="drawing" class="canvasstyle" width="800" height="600"></canvas>
</body>
</html>

BIN
test.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 MiB