Skip to content

Instantly share code, notes, and snippets.

@sirdarthvader
Created April 2, 2018 00:20
Show Gist options
  • Select an option

  • Save sirdarthvader/10abd030fa0f9c6059db7a5ed95dd9eb to your computer and use it in GitHub Desktop.

Select an option

Save sirdarthvader/10abd030fa0f9c6059db7a5ed95dd9eb to your computer and use it in GitHub Desktop.
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = '#BADA55';
ctx.lineWidth = 1;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;
function draw(e) {
if(!isDrawing) {
return; // stop the function when not moused down.
}
console.log(e);
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
hue++;
if(hue>=360){
hue = 0;
}
if(ctx.lineWidth >= 75 || ctx.lineWidth <= 1) {
direction = !direction;
}
if(direction){
ctx.lineWidth++;
} else {
ctx.lineWidth = 1;
}
}
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', ()=> isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment