Teveria
Teveria

Reputation: 1

How to Attach Event to HTML5 Canvas?

So I know you can directly do:

<canvas id="someCanvas" onmousedown="blah();">

<script>
function blah() {
dosomething();
}
</script>

How would I attach the event in code only?

I tried doing:

var canvas = document.getElementById("someCanvas");

canvas.onmousedown = function() {
  doSomething();
}

But it does not work and doSomething does not get called... what am I doing wrong?

Upvotes: 0

Views: 1097

Answers (1)

TJHeuvel
TJHeuvel

Reputation: 12608

Try using AddEventListener, as such:

canvas.addEventListener("mousedown", function() {} );

https://developer.mozilla.org/en/DOM/element.addEventListener

Upvotes: 1

Related Questions