Trying to make buttons create different colored lines on html canvas, but one button doesn't work

Viewed 39

I'm learning about html canvas, and I know how to add lines with different thickness and color, so now, I'm trying to make it so that whenever you press an html button, a line pops up.

I made three buttons; one for a red line, one for a blue line, and one to clear the whole board.

However, only the red line button and the clear button works. Whenever I click the blue line button, nothing happens.

Here's the code:

function redColor(){
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  //ctx.beginPath();  
  ctx.moveTo(200, 0);
  ctx.lineTo(0, 100);
  ctx.lineWidth = 1;
  ctx.strokeStyle = "red";
  ctx.stroke();
}
   
function blueColor(){
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.lineWidth = 4;
  ctx.strokeStyle = "blue";
  ctx.moveTo(0, 0);
  ctx.lineTo(200, 100);
  ctx.stroke();
}
  
function remove(){
  var a = document.getElementById("myCanvas");
  var tx = a.getContext("2d");
  tx.clearRect(0, 0, 200, 100);
} 
canvas {
  border: solid 1px #000;
}
<canvas id="myCanvas" width="200" height="100"></canvas>

<div>
  <button onclick="redColor()">Red</button>
  <button onlick="blueColor()">Blue</button>
  <button onclick="remove()">Clear</button>
</div>
 

2 Answers

You misspelled "onclick"! change it to:

<p>
  <button onclick="redColor()">Red</button>
  <button onclick="blueColor()">Blue</button>
  <button onclick="remove()">Clear</button>
</p>

You spelled onclick as "onlick". I don't know if this makes a difference, but the order of the code is different for red and blue

Related