-2

After window finished loading, I want to add some Javascript to the canvas. I tried this code

<script type="text/javascript">

  window.addEventListener("load", init);

  function init(){
      var canvas = document ...
      canvas.addEventListener("mousedown", onMouseDown);
  }

</script> 

But I get the following error:

ReferenceError: onMouseDown is not defined
DarkTrick
  • 2,447
  • 1
  • 21
  • 39
  • 4
    Why do you think `onMouseDown` should be defined? You haven't defined it anywhere in the code you have written in the question. – Quentin Aug 18 '18 at 09:24
  • I was not familiar enough with addEventListener. The confusing point was when to use "on" and when not. I can call canvas.onMouseDown = function(e) { ... } but The event is called "mousedown". I didn't know, that "mousedown" is the event. I though I would need to implement "mousedown" and "onMouseDown" is the 'event'. – DarkTrick Aug 19 '18 at 00:29
  • You can call your function whatever you like. `onMouseDown`, `mousedown`, `function_to_fun_with_the_mouse_is_down_that_makes_it_rain_puppies`. You still need to define the function you want to run when the event happens. – Quentin Aug 19 '18 at 07:41

3 Answers3

0

You should have a function for onMouseDown like

function onMouseDown() {
// Perform mouse down functions you want here
}
R Ganesh
  • 102
  • 1
  • 9
0

It seems that onMouseDown function is not defined or it's not loaded on the current html file.

You can make sure by opening the debug console in your browser (press F12 in and click on Console tab) and check whether your function exists or not. You just need to type onMouseDown on the browser console and watch the result. If you got RefrenceError, it does mean your function has not written or has not loaded yet.

As you see here, the onMouseDown function hasn't defined on the current document

Nima Boobard
  • 503
  • 2
  • 8
-1

I don't know why, but writing the function directly helped:

function init(){
    var canvas = document ...
    canvas.onmousedown = function(e){
        // bla
    }
}

As in this answer: https://stackoverflow.com/a/10036499

DarkTrick
  • 2,447
  • 1
  • 21
  • 39
  • You can also use `canvas.addEventListener("mousedown", onMouseDown);`, you just have to define the function somewhere e.g. `function onMouseDown(event) { //code here }`. The even listener is looking for a function with that name and not finding it which is exactly what the error is telling you. – luke-codewalker Aug 18 '18 at 09:19