【问题标题】:TypeError: canvas.getContext ('2d') is not a functionTypeError:canvas.getContext('2d')不是函数
【发布时间】:2017-10-15 17:34:33
【问题描述】:

我写了一个简单的jQuery代码:

canvas = $('#canvas'); ctx = canvas.getContext('2d');

并得到“TypeError:canvas.getContext 不是函数”错误。我在这里研究过;虽然有程序员遇到类似问题的类似问题,但他们的背景是不同的。我还在同一行中收到以下附加错误:

at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at Function.ready (jquery.min.js:2) at HTMLDocument.J (jquery.min.js:2)

这是我的 jQ 代码:

$(function () {
var arr_touches = [];
var canvas;
var ctx;
var down = false;
var color = 'black';
var width = 5;

canvas = $('#canvas');
ctx = canvas.getContext('2d');
ctx.lineWidth = width;
canvas.on({
    mousemove: function(e){
    xPos = e.clientX-canvas.offsetLeft;
    yPos = e.clientY-canvas.offsetTop;
   if(down == true)
     {
    ctx.lineTo(xPos,yPos); //create a line from old point to new one
    ctx.strokeStyle = color;
    ctx.stroke();
    }
}, 
mousedown:function(){
    down = true;
    ctx.beginPath();
    ctx.moveTo(xPos, yPos);
}, 
mouseup:function(){
    down = false;
},
//handling mobile touch events
touchstart:function(evt){
    var touches = evt.changedTouches;
    for(var i = 0; i < touches.length; i++) 
       {
           if(isValidTouch(touches[i])) 
              {
               evt.preventDefault();
               arr_touches.push(copyTouch(touches[i]));
               ctx.beginPath();
               ctx.fillStyle = color;
               ctx.fill();
            }
        }
});

【问题讨论】:

    标签: jquery html5-canvas typeerror


    【解决方案1】:

    .getContext() 不是有效的 jquery 方法。它是 HTML 画布元素上的有效方法。参考MDN

    我认为您正在寻找的是:

    canvas = document.getElementById('canvas');
    

    fiddle

    【讨论】:

    • 乐于助人:)
    猜你喜欢
    • 2017-11-19
    • 2016-12-23
    • 1970-01-01
    • 2015-01-04
    • 2018-04-08
    • 2019-03-03
    • 2014-09-27
    • 2017-05-06
    • 2019-12-20
    相关资源
    最近更新 更多