Last active
March 16, 2021 13:29
-
-
Save fredefox/224a0ca611ec65784365867e6b7460be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tau = Math.PI * 2; | |
const getImageData = (ctx, [x0, x1], [y0, y1]) => { | |
const data = ctx.getImageData(x0, x1, y0, y1).data; | |
return Array.from( | |
(function* () { | |
for (let i = 0; i < data.length; i += 4) { | |
yield [data[i], data[i + 1], data[i + 2], data[i + 3]]; | |
} | |
})() | |
); | |
}; | |
const divMod = (a, b) => [Math.floor(a / b), a % b]; | |
const main = () => { | |
// ctx.fillStyle = "green"; | |
// const w = canvas.width / 4; | |
// const h = canvas.height / 4; | |
// ctx.fillRect((canvas.width - w) / 2, (canvas.height - h) / 2, w, h); | |
var img = new Image(100); | |
img.src = "piman.svg"; | |
// img.src = "img.jpg"; | |
img.addEventListener("load", () => { | |
const canvas = document.querySelector("canvas"); | |
const ctx = canvas.getContext("2d"); | |
canvas.width = img.naturalWidth; | |
canvas.height = img.naturalHeight; | |
console.log(img.naturalWidth, img.naturalHeight); | |
ctx.drawImage(img, 0, 0); | |
const data = getImageData(ctx, [0, 0], [canvas.width, canvas.height]); | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
const size = 15; | |
for (let i = 0; i < data.length; i += size) { | |
const [y, x] = divMod(i, img.naturalWidth); | |
if (y % size !== 0) continue; | |
const [r, g, b, a] = data[i]; | |
ctx.beginPath(); | |
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`; | |
ctx.arc(x, y, size / 2, 0, tau); | |
ctx.fill(); | |
} | |
}); | |
}; | |
document.addEventListener("DOMContentLoaded", main); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment