0

I have a canvas on which I am making a menu screen for my game:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

ctx.font="30px monospace";
ctx.fillStyle = "black";
ctx.strokeText("click to begin",140,260);

When the user clicks "click to begin", I want it to progress to my game, but considering that I can't get the onclick working I just want it to alert that it has worked. So far (based off of tutorials and examples I have found) I have the following code:

mouse = (function (target) {
    var isButtonDown = false;

    c.addEventListener('mousedown', function () {
        isButtonDown = true;
    });

    return {
         isButtonDown: function () {
             return isButtonDown;
         }
    };
}(document));

var isButtonDown = input.isButtonDown();

if (isbuttondown == true) {
          alert("Mouse clicked");
}

This code does nothing when I run it. Could someone please explain to me how to get this working, or at least what I need to change?

Thanks in advance,

Riley

Progrmr
  • 1,575
  • 4
  • 26
  • 44
  • http://stackoverflow.com/questions/9880279/how-do-i-add-a-simple-onclick-event-handler-to-a-canvas-element –  Nov 01 '13 at 07:16

1 Answers1

1

Here is a Solution.

Solution

I have removed the alert and instead used console.log. Check the console.

JS

canvas.addEventListener('click', function (evt) {
    var mousePos = getMousePos(canvas, evt);
    var message = 'Mouse Clicked at ' + mousePos.x + ',' + mousePos.y;
    console.log(message);
}, false);

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

EDIT: Here is the same fiddle with Alert option. FIDDLE

MarsOne
  • 2,155
  • 5
  • 29
  • 53