summaryrefslogtreecommitdiff
path: root/draw.js
diff options
context:
space:
mode:
authorJules Laplace <julescarbon@gmail.com>2017-08-21 00:05:40 +0200
committerJules Laplace <julescarbon@gmail.com>2017-08-21 00:05:40 +0200
commitab925dc86c3bd03d730f2740600bf3d93ac23190 (patch)
tree4eb2c03c8487e0846a8e055032534000dde14d51 /draw.js
init
Diffstat (limited to 'draw.js')
-rw-r--r--draw.js99
1 files changed, 99 insertions, 0 deletions
diff --git a/draw.js b/draw.js
new file mode 100644
index 0000000..53cd673
--- /dev/null
+++ b/draw.js
@@ -0,0 +1,99 @@
+var draw = $(function(){
+ var draw = {}
+
+ var drawing = false, lastPoint
+ var brushColor = 0, brushColors = ['#000','#888','#fff']
+
+ var canvas = $('#imageColour').get(0)
+ var ctx = canvas.getContext('2d')
+ ctx.fillStyle = '#fff'
+ ctx.fillRect(0, 0, canvas.width, canvas.height)
+
+ var brush = document.querySelector('#brush')
+ var brushCtx = brush.getContext('2d')
+ resizeBrush(2, 2)
+
+ function down(e) {
+ drawing = true
+ lastPoint = toCoord(e)
+ stamp(lastPoint)
+ }
+ function move(e) {
+ if (! drawing) return
+ var point = toCoord(e)
+ line(lastPoint, point)
+ lastPoint = point
+ }
+ function up(e) {
+ drawing = false
+ render()
+ }
+
+ function toCoord(e) {
+ return {
+ x: e.pageX - canvas.offsetLeft,
+ y: e.pageY - canvas.offsetTop,
+ }
+ }
+ function line(a, b) {
+ var len = dist(a.x, a.y, b.x, b.y)
+ var bw = 1
+ var x, y, i;
+ for (var i = 0; i <= len; i += bw) {
+ x = lerp(i / len, a.x, b.x)
+ y = lerp(i / len, a.y, b.y)
+ stamp({ x, y })
+ }
+ }
+ function stamp(p) {
+ var xx = Math.floor(p.x - brush.width/2)
+ var yy = Math.floor(p.y - brush.height/2)
+ ctx.drawImage(brush, xx, yy)
+ }
+ function resizeBrush(w, h) {
+ brush.width = clamp(w, 1, 50)
+ brush.height = clamp(h, 1, 50)
+ brushCtx.fillStyle = brushColors[brushColor]
+ brushCtx.fillRect(0, 0, brush.width, brush.height)
+ }
+
+ function lerp(n,a,b){ return (b-a)*n+a }
+ function dist(x0,y0,x1,y1){ return Math.sqrt(Math.pow(x1-x0,2) + Math.pow(y1-y0,2)) }
+ function clamp(n,a,b){ return n<a?a:b<n?b:n }
+
+ $('#imageColour').on({
+ mousedown: down,
+ touchstart: untouch(down),
+ })
+ $('body').on({
+ mousemove: move,
+ touchmove: untouch(move),
+ mouseup: up,
+ })
+ document.body.addEventListener('touchmove', function(e){
+ e.preventDefault()
+ })
+ function untouch(f){ return (e) => f(e.originalEvent.touches[0]) }
+ $('body').on('keydown', (e) => {
+ if (e.target === input) return
+ // console.log(e.keyCode)
+ switch (e.keyCode) {
+ case 39: // right
+ case 38: // up
+ case 221: // right bracket
+ resizeBrush(brush.width+1, brush.height+1)
+ break
+ case 37: // left
+ case 40: // down
+ case 219: // left bracket
+ resizeBrush(brush.width-1, brush.height-1)
+ break
+ case 88: // x
+ brushColor = (brushColor + 1) % brushColors.length
+ resizeBrush(brush.width, brush.height)
+ break
+ }
+ })
+
+ return draw
+}) \ No newline at end of file