无法阅读属性' clientX'未定义,使用jquery

时间:2016-07-16 02:50:55

标签: javascript jquery html5 html5-canvas

您好我正在尝试学习如何使用HTML5画布绘制应用程序 我写了这段代码到目前为止,事情是浏览器控制台一直告诉我,无法读取属性' clientX'未定义的,我当然使用jquery

这是JS代码:

var canvas;
var context;


function getMousePos(e) {
    var canBoundX = canvas.offsetLeft;
    var canBoundY = canvas.offsetTop;
    var x = e.clientX - canBoundX,
        y = e.clientY - canBoundY;

    return {x: x, y: y};
}


function drag_click() {
    console.log(getMousePos());
}

function drag() {
    console.log(getMousePos());
}

function drag_stop() {
    console.log(getMousePos());
}

function draw() {
    canvas = $("#mainCanvas")[0];
    context = canvas.getContext('2d');
    context.strokeStyle =  "#000";
    context.lineWidth = 4;
    context.lineCap = "round";

    $(canvas).mousedown(function (e) {
        drag_click();
    });
    $(canvas).mousemove(function (e) {
        drag();
    });
    $(canvas).mouseup(function (e) {
        drag_stop();
    });
}


$(document).ready(draw()); 

1 个答案:

答案 0 :(得分:3)

您必须在函数edraw_clickdraw以及函数draw_stop中传递参数get_mouse_pos。如果不传递任何参数,则在函数get_mouse_pos中,变量eundefined

var canvas;
var context;


function getMousePos(e) {
    var canBoundX = canvas.offsetLeft;
    var canBoundY = canvas.offsetTop;
    var x = e.clientX - canBoundX,
        y = e.clientY - canBoundY;

    return {x: x, y: y};
}


function drag_click(e) {
    console.log(getMousePos(e));
}

function drag(e) {
    console.log(getMousePos(e));
}

function drag_stop(e) {
    console.log(getMousePos(e));
}

function draw() {
    canvas = $("#mainCanvas")[0];
    context = canvas.getContext('2d');
    context.strokeStyle =  "#000";
    context.lineWidth = 4;
    context.lineCap = "round";

    $(canvas).mousedown(function (e) {
        drag_click(e);
    });
    $(canvas).mousemove(function (e) {
        drag(e);
    });
    $(canvas).mouseup(function (e) {
        drag_stop(e);
    });
}


$(document).ready(draw());