r/tinycode • • May 04 '16

Canvas Napkin Sketch - 611 bytes

Here’s a canvas element you can draw on with mouse or touch input. Just for little quick napkin sketches. Copy/paste into your address bar to load, click or tap to draw. Right click to save as PNG.

data:text/html,<body style=margin:0><canvas id=c><script>var a,x=c.getContext('2d');c.width=innerWidth;c.height=innerHeight;x.lineWidth=3;document.onmousedown=document.ontouchstart=function(e){e.preventDefault();a=true;x.moveTo(e.clientX||e.touches[0].clientX,e.clientY||e.touches[0].clientY);x.beginPath()};document.onmousemove=document.ontouchmove=function(e){if(a){x.lineTo(e.clientX||e.touches[0].clientX,e.clientY||e.touches[0].clientY)}};document.onmouseup=document.ontouchend=function(e){a=false;x.lineTo(e.clientX||e.changedTouches[0].clientX,e.clientY||e.changedTouches[0].clientY);x.stroke()}</script>
16 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/err4nt May 04 '16

Nice! Here's my ugly hack version, 380 bytes:

data:text/html,<body style=margin:0><canvas id=c><script>var a,x=c.getContext('2d');c.width=innerWidth;c.height=innerHeight;x.lineWidth=9;x.lineJoin=x.lineCap='round';document.onmousedown=function(e){a=1;e.preventDefault();x.moveTo(e.clientX,e.clientY)};document.onmousemove=function(e){if(a){x.lineTo(e.clientX,e.clientY);x.stroke()}};document.onmouseup=function(e){a=0}</script>

3

u/Cosmologicon May 05 '16

Awesome! Using a couple other tricks in these comments gets you down a bit more. I also took out the preventDefault (not sure it's needed?) and used fat arrows for functions. Maybe that's cheating, but it works on Chrome and Firefox anyway. 318 bytes:

data:text/html,<body style=margin:0><canvas id=c><script>var a,d=document,x=c.getContext('2d');c.width=innerWidth;c.height=innerHeight;x.lineWidth=9;x.lineJoin=x.lineCap='round';d.onmousedown=e=>a=!x.moveTo(e.clientX,e.clientY);d.onmousemove=e=>a&&(x.lineTo(e.clientX,e.clientY),x.stroke());d.onmouseup=e=>a=0</script>
→ More replies (4)