By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 1,825 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

How to reference canvas inside a function's scope?

P: 2
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?

Expand|Select|Wrap|Line Numbers
  1. var c = document.getElementById("canvas1");
  2. var ctx = c.getContext("2d");
  3.  
  4. var isDrawing = false;
  5. var mX, mY, rX, rY;
  6.  
  7. function InitThis() {
  8.  
  9.     c.onmousedown = function(e) {
  10.       isDrawing = true;
  11.       mX = e.clientX;
  12.       mY = e.clientY;
  13.       };
  14.  
  15.     c.onmousemove = function(e) {
  16.         if (isDrawing) {
  17.           rX = e.clientX;
  18.           rY = e.clientY;
  19.           draw();
  20.           ctx.clearRect(0, 0, canvas.width, canvas.height);
  21.         }
  22.     };
  23.  
  24.     c.onmouseup = function(e) {
  25.       rX = e.clientX;
  26.       rY = e.clientY;
  27.       isDrawing = false;
  28.   }
  29. }
  30.  
  31. function draw() {  
  32.     ctx.beginPath();
  33.     ctx.moveTo(mX,mY);
  34.     ctx.lineTo(rX, rY);
  35.     ctx.closePath();
  36.     ctx.stroke();
  37. }
  38. InitThis()

The error: "ReferenceError: canvas is not defined
at HTMLCanvasElement.InitThis.c.onmousemove (zivuqeyure.js:22:31)"


Any idea how can I fix this?
Dec 13 '17 #1
Share this Question
Share on Google+
2 Replies


gits
Expert Mod 5K+
P: 5,268
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.
Dec 13 '17 #2

P: 2
Silly me, indeed! Changed it to
Expand|Select|Wrap|Line Numbers
  1.  ctx.clearRect(0, 0, ctx.width, ctx.height)
and I no longer get error. Thank you!
Dec 14 '17 #3

Post your reply

Sign in to post your reply or Sign up for a free account.