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 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 })