Canvas How to - Control canvas with button








Question

We would like to know how to control canvas with button.

Answer


<!DOCTYPE html>
<html>
<body>
  <canvas id="progress"></canvas>
  <br />
  <button onclick="context.fillRect(0, 0, progressWidth*0.33, 18);">make
    33%</button>
  <button onclick="context.fillRect(0, 0, progressWidth*0.5, 18);">then
    make 50%</button>
  <button onclick="context.fillRect(0, 0, progressWidth*1, 18);">at
    last make 100%</button>
  <script type='text/javascript'>
canvas = document.getElementById("progress"),
context = canvas.getContext("2d");
progressWidth = 200;<!--from   w  w  w .  j a  va 2 s  .  c  om-->
context.fillStyle = 'lighgray';
context.fillRect(0, 0, progressWidth, 18);
context.moveTo(0, 0);
context.fillStyle = 'darkgray';
context.fillRect(0, 0, 1, 18);

</script>
</body>
</html>

The code above is rendered as follows: