登录 | 注册 | FAQ
Anonymous

Referencing canvas inside a function's scope

+ 发表回复

2 篇帖子 分页: 1 / 1


Referencing canvas inside a function's scope

greg79 » 周三 12月 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?


代码: 全选
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?
头像

greg79

  • 帖子: 1
  • 注册: 周三 12月 13, 2017 6:20 pm

Re: Referencing canvas inside a function's scope

taynguyenem » 周一 2月 05, 2018 3:33 pm

Hi
You need add link to js of canvas.
Ex: https://cdnjs.cloudflare.com/ajax/libs/ ... anvasjs.js
Hope it help to you.
头像

taynguyenem

  • 帖子: 20
  • 注册: 周一 2月 05, 2018 3:28 pm
--
Preview site only Html: teamviewdownload.com, winrarfree.net


+ 发表回复

分页: 1 / 1