Anmelden | Registrieren | FAQ
Anonymous

Referencing canvas inside a function's scope

+ Antwort erstellen

1 Beitrag Seite 1 von 1


Referencing canvas inside a function's scope

von greg79 » Mi Dez 13, 2017 6:25 pm

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: Alles auswählen
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 HTMLCanvasElement.InitThis.c.onmousemove (zivuqeyure.js:22:31)"



Any idea how can I fix this?
Benutzeravatar

greg79

  • Beiträge: 1
  • Registriert: Mi Dez 13, 2017 6:20 pm


+ Antwort erstellen

Seite 1 von 1