HTML5 Canvas Fun
by Pranab Dey
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d'),x=0, y=0, isDrawing, hue=0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.border = '1px solid red';
canvas.onmousedown = (e)=>{
isDrawing = true;
x = e.offsetX; y = e.offsetY;
draw();
}
canvas.onmouseup = ()=>{
isDrawing = false;
draw();
}
ctx.lineWidth = 10;
function draw(){
if(isDrawing===true){
canvas.onmousemove = e=>{
console.log([x, e.clientX, y, e.clientY]);
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
hue++;
if(hue>=360){
hue=0;
}
[x, y] = [e.offsetX, e.offsetY];
console.log(ctx.lineWidth);
};
}
else{
canvas.onmousemove = ()=>{
ctx.beginPath();
};
}
}
canvas.onmouseout =()=>{
canvas.onmousemove = ()=>{
ctx.beginPath();
};
}
ctx.lineCap = 'round';
ctx.lineJoin = 'round';