Obfuscated Canvas Commands
const oCan = (
d = document,
b = d.body,
canvas = b.appendChild(document.createElement('canvas')),
c = canvas.getContext('2d'),
props = [],
o = {},
docs = {},
cmds = [],
L,
k,
du,
j,
draw,
id
) => {
;(onresize = () => {
canvas.width = innerWidth
canvas.height = innerHeight
if (draw) {
clearTimeout(id)
id = setTimeout(() => cmds.forEach(v => draw(v)), 500)
}
})()
Object.assign(b.style, { margin: 0, height: '100%' })
// longer way: console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(c)));
for (let i in c) props.push(i)
// make alphabetical since object keys have
// no order
props.sort().map(i => {
L = i.match(/[A-Z]/)
k = i[0]
if (L) k += L[0]
du = 0
if (o[k]) {
j = 0
while (o[k]) k += i[++j]
}
o[k] =
(typeof c[i])[0] == 'f'
? (...args) => c[i].apply(c, args)
: v => (c[i] = v)
docs[i] = k
})
console.log('docs:', JSON.stringify(docs, null, 2))
return (draw = (s, cmd, currFn, args = [], part, fn, num) => {
cmd = s.split(/\s+/)
cmds.push(s)
c.save()
for (let i = 0; i < cmd.length; i++) {
part = cmd[i]
fn = o[part]
if (fn && currFn != fn) {
currFn && currFn.apply(c, args)
currFn = fn
args = []
} else {
num = parseFloat(part)
args.push(!isNaN(num) ? num : part)
}
}
currFn && currFn.apply(c, args)
c.restore()
})
}
const c = oCan()
// `font` & text not suppoted
// make str a function so resize works?
c(`
fS #ccc
fR 0 0 400 ${innerHeight}
fS blue
fR 40 0 20 20
gCl difference
ro .25
fR 50 0 30 30
gCl source-over
fS rgba(200,100,9)
fR 100 100 40 40
`)
I’ve had this idea for a long time, never bothered doing it until now. I wrote it in a semi-golfed style for no reason… Anyway, this lets you write canvas code in a strange obfuscated syntax that looks like this:
c(`
fS #ccc
fR 0 0 400 ${innerHeight}
fS blue
fR 40 0 20 20
gCl difference
ro .25
fR 50 0 30 30
gCl source-over
fS rgba(200,100,9)
fR 100 100 40 40
`)
This snippet logs out some JSON that shows all the method aliases for the canvas context.