How to reference canvas inside a function's scope?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • greg79
    New Member
    • Dec 2017
    • 2

    How to reference canvas inside a function's scope?

    I get error with this code, it seems like ctx is not known inside the function. How can I reference the canvas from within the function?

    Code:
    var c = document.getElementById("canvas1");
    var ctx = c.getContext("2d");
    
    var isDrawing = false;
    var mX, mY, rX, rY;
    
    function InitThis() {
    
        c.onmousedown = function(e) {
          isDrawing = true;
          mX = e.clientX;
          mY = e.clientY;
          };
    
        c.onmousemove = function(e) {
            if (isDrawing) {
              rX = e.clientX;
              rY = e.clientY;
              draw();
              ctx.clearRect(0, 0, canvas.width, canvas.height);
            }
        };
    
        c.onmouseup = function(e) {
          rX = e.clientX;
          rY = e.clientY;
          isDrawing = false;
      }
    }
    
    function draw() {  
        ctx.beginPath();
        ctx.moveTo(mX,mY);
        ctx.lineTo(rX, rY);
        ctx.closePath();
        ctx.stroke();
    }
    InitThis()

    The error: "ReferenceError : canvas is not defined
    at HTMLCanvasEleme nt.InitThis.c.o nmousemove (zivuqeyure.js: 22:31)"


    Any idea how can I fix this?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    well - if that's your error message - then look closer at it. its says:

    canvas is not defined

    so from the code you posted look at line 20 where you use canvas while i dont see you define it before? So that's probably that issue.

    Comment

    • greg79
      New Member
      • Dec 2017
      • 2

      #3
      Silly me, indeed! Changed it to
      Code:
       ctx.clearRect(0, 0, ctx.width, ctx.height)
      and I no longer get error. Thank you!

      Comment

      Working...