Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72358

Changing colors of stroke in canvas

$
0
0

I have just started to play with some JavaScript and I found thing called canvas.

My problem is that after the click on a button I want to change the color of stroke, but I dont know how. I'm out of ideas but still I think it should be some easy solution that I'm not seeing.

If anyone can help, I would be happy. Thank you.

  const canvas = document.querySelector('#draw');
  // could be 3d, if you want to make a video game
  const ctx = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  ctx.lineJoin = 'round';
  ctx.lineCap = 'round';
  ctx.lineWidth = 20;

  var color = "blue";

  console.log(color)

  ctx.strokeStyle = color;

  let isDrawing = false;
  let lastX = 0;
  let lastY = 0;


  function draw(e, color) {
    // stop the function if they are not mouse down
    if(!isDrawing) return;
    //listen for mouse move event

    console.log(color)
    ctx.strokeStyle = color;

    console.log(e);
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(e.offsetX, e.offsetY);
    ctx.stroke();
    [lastX, lastY] = [e.offsetX, e.offsetY];
  }

  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);
<div><button id="red" style="width: 50px; height: 50px; border-radius: 50%; background-color: red" onclick="draw(this.id)"></button><button id="blue" style="width: 50px; height: 50px; border-radius: 50%; background-color: blue" onclick="draw(this.id)"></button><button id="green" style="width: 50px; height: 50px; border-radius: 50%; background-color: green" onclick="draw(this.id)"></button><canvas id="draw" width="100" height="100"></canvas></div>

Viewing all articles
Browse latest Browse all 72358

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>