#JavaScript30 HTML5 Canvas

In this example below you will see how to do a #JavaScript30 HTML5 Canvas with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by quasiturtle, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright quasiturtle ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>#JavaScript30 HTML5 Canvas</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <canvas id="draw" style="background: black;"></canvas>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/quasiturtle/javascript30-html5-canvas-zWNGPB */
html, body {
    margin:0;
  }

/*Downloaded from https://www.codeseek.co/quasiturtle/javascript30-html5-canvas-zWNGPB */
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;

let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;


function draw(e) {
  if (!isDrawing) return;
  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 >= 100 || ctx.lineWidth <= 5) {
    direction = !direction;
  }
  
  if (direction) {
    ctx.lineWidth++;
    }
  else {
    ctx.lineWidth--;
       }
}

canvas.addEventListener('mousedown', (e) => {
    isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];
});

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

Comments