document.onmousedown = handleMouseDown document.onmouseup = () => drawing = false; document.onmousemove = handleMouseMove; var drawing = false paths = [] function start() { canvas.start(); } var canvas = { canvas: document.createElement("canvas"), start: function () { this.canvas.ontouchmove = handleTouchMove this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight -4; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.frameNo = 0; this.interval = setInterval(updateCanvas, 50); this.context.beginPath(); this.context.moveTo(window.innerWidth/2, 50) }, clear: function () { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } } function updateCanvas() { variance = 20 ctx = canvas.context for(i = 0; i < paths.length; i++){ ctx.beginPath() ctx.moveTo(paths[i].x, paths[i].y) rand = Math.random()*variance*2 - variance paths[i].x = paths[i].x + rand paths[i].y = paths[i].y + Math.sqrt(variance * variance - rand*rand) ctx.lineTo( paths[i].x , paths[i].y ) ctx.strokeStyle = paths[i].color ctx.stroke() if(paths[i]. y > canvas.canvas.height){ paths.splice(i, 1) i-- } } } function handleTouchMove(event) { x = clamp(event.touches[0].pageX - canvas.canvas.getBoundingClientRect().left, 0, canvas.canvas.width) y = clamp(event.touches[0].pageY - canvas.canvas.getBoundingClientRect().top, 0, canvas.canvas.height) paths.push({x: x, y:y, color:"black"/*getRandomColor()*/}) } function handleMouseMove(event) { addPath(event) } function handleMouseDown(event) { drawing = true; addPath(event) } function addPath(event){ if (drawing) { x = clamp(event.x - canvas.canvas.getBoundingClientRect().left, 0, canvas.canvas.width) y = clamp(event.y - canvas.canvas.getBoundingClientRect().top, 0, canvas.canvas.height) paths.push({ x: x, y: y, color: "black"/*getRandomColor()*/ }) } } function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } function clamp(num, min, max) { return num <= min ? min : num >= max ? max : num } function cos(num) { return Math.cos(num * Math.PI / 180) } function sin(num) { return -1 * Math.sin(num * Math.PI / 180) } function isColliding(x1, y1, w1, h1, x2, y2, w2, h2) { return x1 < x2 + w2 && x1 + w1 > x2 && y1 < y2 + h2 && y1 + h1 > y2 }