0

here comes my code first..

<canvas id="myCanvas" width="640" height="480">

</canvas>




<script type="text/javascript">
    // Javascript Goes Here
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var width = canvas.getAttribute('width');
    var height = canvas.getAttribute('height');

    //Images variables
    var bgImage = new Image();
    var playImage = new Image();
    var shipImage = new Image();
    var instructImage = new Image();
    var logoImage = new Image();

    //Arrays for position of Images
    var buttonX = [196, 196, 150, 160];
    var buttonY = [100, 140, 12, 150];
    var buttonWidth = [96, 260, 182, 160];
    var buttonHeight = [40, 40, 40, 40];




    //Source of Images
    bgImage.src = "Images/Background.png";
    playImage.src = "Images/play.png";
    //shipImage.src = "Images/enemy.png";
    instructImage.src = "Images/instructions.png";
    logoImage.src = "Images/logo.png";



    //drawing Images 
    bgImage.onload = function () {
        context.drawImage(bgImage, 0, 0);
    };
    playImage.onload = function () {
        context.drawImage(playImage, buttonX[0], buttonY[0]);
    };
    instructImage.onload = function () {
        context.drawImage(instructImage, buttonX[1], buttonY[1])
    }
    logoImage.onload = function () {
        context.drawImage(logoImage, buttonX[2], buttonY[2])
    }
    //shipImage.onload = function () {
    //    context.drawImage(shipImage, buttonX[3], buttonY[3])
    //}

What i want to have is a simple ClickListener on the play and instruction image. I´ve tried many options and tutorials but nothing works.... Could anybody help me please? Thanks a lot!

  • try this. It's a bit complex but i believe its a good start http://stackoverflow.com/questions/9880279/how-do-i-add-a-simple-onclick-event-handler-to-a-canvas-element – Dhiraj Mar 19 '15 at 18:00

1 Answers1

0

You can use the following to register the handlers:

playImage.addEventListener("click", function(){
  alert("Play was clicked.");
});

instructImage.addEventListener("click", function(){
  alert("Instruct was clicked.");
});

Alternatively, this may also work for you:

playImage.onclick = function() { alert("Play was clicked."); };
instructImage.onclick = function () { alert("Instruct was clicked."); };

If that doesn't work for you, describe your expectations and how they aren't met by this answer.

Also, the following link to the MDN would help you with syntax questions like this in the future.

Tyler Kendrick
  • 418
  • 6
  • 18
  • Thanks for your comment. I am not very good at programming..so where should i drop the code ? I think i must write a new function or? – Patta Gatta Mar 19 '15 at 18:47
  • Used another option :) http://code.tutsplus.com/tutorials/animating-game-menus-and-screen-transitions-in-html5-a-guide-for-flash-developers--active-11183 – Patta Gatta Mar 19 '15 at 19:05