title: Creating a button on an HTML5 canvas using JavaScript
body: <p>I'm trying to write a simple game to teach some basic Welsh using the HTML5 canvas and JavaScript.</p>
  
  <p>I currently have a web page, which displays a canvas, and on the canvas, the 'start button' has been drawn, which the user will click to start the game.</p>
  
  <p>I now want to add the functionality to that button, so that when the user clicks it, the first level of the game is displayed on the canvas. However, I'm having a bit of trouble with this, and was wondering if someone could help me out.</p>
  
  <p>I have the following code in my index.html file:</p>
  
  <p>In a hidden section in the head, I have:</p>
  
  <pre><code>&lt;section hidden&gt;
  &lt;img id="StartButton" src="StartButton.png" alt="Start Button" width="179" height="180" /&gt;
  
  &lt;script type="text/javascript"&gt;
      /* Create a canvas layer to display text */
      function displayText(textLayer, message){
          var textLayerContext = textLayer.getContext();
          textLayer.clear();
          textLayerContext.font = "18pt Calibri";
          textLayerContext.fillStyle = "black";
          textLayerContext.fillText(message, 10, 10);
      }
  
      /* Create a canvas layer to display the button */
      window.onload = function(){
          var stage = new Kinetic.Stage({
              container: "container",
              width: 179,
              height: 180
          });
          var buttonLayer = new Kinetic.Layer();
          var textLayer = new Kinetic.Layer();
  &lt;/script&gt;
  
  
  &lt;/section&gt;
  </code></pre>
  
  <p>In the body onLoad... I have a call to the function startGame(), and then have the following code within the body tags:</p>
  
  <pre><code>&lt;body onLoad="startGame()"&gt;
      &lt;h1&gt;Home&lt;/h1&gt;
      &lt;p1&gt;The purpose of this website is to allow users to learn some basic Welsh by playing the game below. &lt;br /&gt;&lt;br /&gt;&lt;/p1&gt;
      &lt;p2&gt;
  
      &lt;canvas id="gameCanvas" width="700" height="300" style="border:1px dotted"&gt;
      Your browser does not support the canvas element.
      &lt;/canvas&gt;
  
      &lt;script type="text/javascript"&gt;
          /* Create the canvas, and add some global variables. */
          var myGameCanvas = document.getElementById("gameCanvas");
          var context = myGameCanvas.getContext("2d");
          var image = new Image();
          var imageSource;
          var imageX;
          var imageY;
  
          /* Global variables- game elements */
          var currentLevel=1;
          var totalLevels=5;
          var currentScore=0;
          var currentScorePositionX=100;
          var currentScorePositionY=100;
  
  
          /* This function starts the game, and calls all of the other functions required to play the game */
          function startGame(){
              drawGameElements();
              drawStartButton(); 
              /* Now need to add an event listener to call drawLevelOneElements() when
                  the start button is clicked. */
              myGameCanvas.addEventListener("click", drawLevelOneElements, false);
              //drawLevelOneElements();
              //game_id=setInterval(game_loop, 50);
          }
  
          /* This function draws the game elements */
          function drawGameElements(){
  
              /* Draw a line for the 'score bar'. */
              context.moveTo(0, 25);
              context.lineTo(700, 25);
              context.stroke();
  
              /* Draw current level/ total levels on the left, and current score on the right. */
              context.font = "11pt Calibri"; /* Text font &amp; size */
              context.strokeStyle = "black"; /* Font colour */
              context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
              context.strokeText(currentScore, 650, 15);
          }
  
          /* This function draws a start button which the user can click to start the game */
          function drawStartButton(){
              image.onload = function(){
                  context.drawImage(image, 260.5, 60);
              };
              image.src = "StartButton.png";
              /** Now I need to add an event listener to the area of the canvas on 
                  on which the button image is displayed, in order to 'listen' for 
                  a click on the button */
              var boundingBox = myGameCanvas.getBoundingClientRect();
              var mouseX = (mouse_event.clientX-boundingBox.left) * (myGameCanvas.width/boundingBox.width);
              var mouseY = (mouse_event.clientY-boundingBox.top) * (myGameCanvas.height/boundingBox.height);
              var pixels = context.getImageData(mouseX, mouseY, 1, 1);
  
              /** There maybe more than one pixel at this location so use a loop
                  to test whether any of the pixels have an alpha value greater than
                  0. With pixel data, 3 is alpha, so check data[3] and every fourth
                  element in data after that. */
              //for (var i=3; i&lt;pixels.data.length; i+=4;){
                  /** If a non- zero alpha is found, stop and return "true"- the click
                      was on a part of the canvas that has colour on it. */
              //  if(pixels.data[i]!=0) return true;
              //}
  
              /** If the function gets here, then the mouse click wasn't on a painted
                  part of the canvas. */
              //return false;
              /**myGameCanvas.getElementById("StartButton").onClick = function(e){
                  drawLevelOneElements();
              } */                
          }
  
  
          /* This function draws the elements for level 1. */
          function drawLevelOneElements(){
              var context = canvas.getContext("2d");
  
              /* Draw the images for numbers 1-10.*/
              var image1 = new Image();
              /* Test that this code is being executed */
              context.moveTo(300, 300);
              context.font = "11pt Calibri";
              context.strokeStyle = "black";
              context.strokeText("Testing",300, 300);
              /* End of test */
  
              image1.onLoad = function(){
                  context.drawImage(image1, 50, 50);
                  };
              image1.src="1.png";
          }
  
          /* This function is what will be used to draw the images on the canvas */
          function drawImage(x, y){
              var numberImage = new Image();
              numberImage.src = imageSource;
              context.drawImage(numberImage, x, y);
  
          }
  
      &lt;/script&gt;
      &lt;br /&gt;&lt;br /&gt;&lt;/p2&gt;
      &lt;p3&gt;Use this paragraph to enter text that provides the user with instructions for how to play the game. &lt;br /&gt;
          Update the instructions so that they're appropriate to whatever level the user is currently playing.&lt;/p3&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>Currently, when I view the page in the browser, I have a 'start button' displayed in the canvas, as I mentioned above. What I can't work out, is how to get the canvas to call the function drawLevelOneElements() when the start button is clicked... I'd be very grateful if someone could please point me in the right direction?</p>
  
  <p>Thanks in advance!</p>
  
  <p>Thanks for your reply. I've tried making the changes you suggested, so I now have:</p>
  
  <pre><code> function startGame(){
              drawGameElements();
              drawStartButton(); 
              /* Now need to add an event listener to call drawLevelOneElements() when
                  the start button is clicked. */
              //myGameCanvas.addEventListener("click", drawLevelOneElements, false);
              //drawLevelOneElements();
              //game_id=setInterval(game_loop, 50);
              /*Add event listener to the canvas */
              myGameCanvas.addEventListener('click', function(e){
                  console.log('click: ' + e.offsetX + '/' + e.offsetY);
                  var buttonHit = collides(StartButton, e.offsetX, e.offsetY);
                  if(buttonHit){
                      alert('collision: ' + buttonHit.x + '/' + buttonHit.y);
                  } else {
                      console.log('no collision');
                  }
              }, false);
          }
  </code></pre>
  
  <p>but when I view the page in the browser, I still just have the canvas with the start button image displayed, and no functionality... i.e. clicking doesn't do anything...</p>
  
  <p>Any suggestions?</p>