JavaScript 30- Day 8 Study Notes

Jeffrey Amen
2 min readNov 17, 2020

--

https://javascript30.com/

Day 8 of JavaScript 30 by Wes Bos introduced me to HTML5 Canvas which is an API to allow you to draw designs either static or dynamically on a webpage. It also can make animations. Bos did a simple dynamic drawing app and did not cover animations.

If you want a more complete course on HTML 5 Canvas, check out Brad Travesy’s HTML5 Canvas Crash Course on YouTube.

To start, we need to access the API. This is done in the body of the HTML code. The size of the canvas is also set.

<canvas id="draw" width="800" height="800">/canvas>

Now within the script tags, Bos set the contexts of the canvas.

const canvas = document.querySelector('#draw');const ctx = canvas.getContext('2d');canvas.width = window.innerWidth;canvas.height = window.innerHeight;ctx.strokeStyle ='#BADA55';ctx.lineJoin = 'round';ctx.lineCap = 'round';ctx.lineWidth = 100;ctx.globalCompositeOperation = 'multiply'; //blend mode

Adding event listeners to detect mouse movement.

canvas.addEventListener('mousemove',draw);canvas.addEventListener('mouseup', ()=> isDrawing = false);canvas.addEventListener('mouseout', ( )=> isDrawing = false);

Passing the event into a function.

function draw(e) {   if(!isDrawing) return; //stop function   ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; //color spectrum   ctx.beginPath(); //start drawing    ctx.moveTo(lastX, lastY);  //start drawing from   ctx.lineTo(e.offsetX, e.offsetY);  //go to   ctx.stroke();    [lastX, lastY]=[e.offsetX,e.offsetY]; //resests start point   hue++; //increments hue setting   if(hue >= 360){      hue = 0; //resets hue   }   if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1){      direction = !direction;   }  //increments line width    if(direction){       ctx.lineWidth++;    }else {       ctx.lineWidth--;    }  //line width increments with directional change}

HTML5 Canvas is new to me. I am looking forward to learning more and creating something interesting soon.

View some other posts in this series.

--

--

Jeffrey Amen

Retired physician, writer, aspiring website designer and developer