Created
February 26, 2023 02:17
-
-
Save bazzargh/d1c43af1b2ed2c278d81d60b78f7ed37 to your computer and use it in GitHub Desktop.
code generating a sketch of mark twain. This should really be in codepen
This file contains hidden or 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
<canvas id="image" width=374 height=480> | |
</canvas> | |
<canvas id="sketch" width=374 height=480> | |
</canvas> |
This file contains hidden or 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 img = new Image(); | |
img.crossOrigin = "anonymous"; | |
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Twain1909.jpg/374px-Twain1909.jpg"; | |
const canvas = document.getElementById("image"); | |
const ctx = canvas.getContext("2d"); | |
const sk = document.getElementById("sketch"); | |
const sketch = sk.getContext("2d"); | |
function gray9(c, x, y) { | |
let d = c.getImageData(x, y, 3, 3).data; | |
let gray = []; | |
for (let i = 0; i < 9; i++) { | |
gray[i] = 0.299*d[4*i] + 0.587*d[4*i + 1] + 0.114*d[4*i + 2]; | |
} | |
return gray; | |
} | |
function gx(a) { | |
return -a[0]+a[2]-2*a[3]+2*a[5]-a[6]+a[8]; | |
} | |
function gy(a) { | |
return -a[0]-2*a[1]-a[2]+a[6]+2*a[7]+a[8]; | |
} | |
function styleFor(g) { | |
if (g > 128 && Math.random() < (240-g)/80) { | |
return 'white' | |
} else if (g < 128 && Math.random() > (g-40)/80) { | |
return 'black' | |
} | |
return 'gray' | |
} | |
img.addEventListener("load", () => { | |
ctx.drawImage(img, 0, 0); | |
img.style.display = "none"; | |
sketch.fillStyle = "gray"; | |
sketch.fillRect(0, 0, 374, 480); | |
let theta,x1,y1; | |
for(var i = 0; i < 50000; i++) { | |
console.log(theta) | |
if (Math.random() < .1 || theta == null) { | |
x1=Math.floor(Math.random() * 374); | |
y1=Math.floor(Math.random() * 480); | |
theta=null | |
} else { | |
x1 = Math.min(374, Math.max(0, Math.floor(x1 + (Math.random() * 17) - 9))); | |
y1 = Math.min(480, Math.max(0, Math.floor(y1 + (Math.random() * 17) - 9))); | |
} | |
let a = gray9(ctx, x1, y1); | |
let dx = gx(a); | |
let dy = gy(a); | |
if (Math.abs(dx)+Math.abs(dy) > 60) { | |
theta = Math.atan2(dy, dx) + Math.PI/2; | |
} else if (theta==null) { | |
continue; | |
} | |
let r=Math.random()*8+2; | |
dx=r*Math.cos(theta); | |
dy=r*Math.sin(theta); | |
sketch.beginPath(); | |
sketch.strokeStyle = styleFor(a[4]) | |
sketch.moveTo(x1-dx, y1-dy); | |
sketch.lineTo(x1+dx, y1+dy); | |
sketch.stroke(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment