J. Duo J. Duo - 4 months ago 40
Javascript Question

Cannot read property 'clientX' of undefined, using jquery

Hello so i am trying to learn how to do a drawing app using HTML5 canvas
and i wrote this code so far, the thing is the browser console keeps telling me that Cannot read property 'clientX' of undefined, i am using jquery of course

here is the JS code:

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());

Answer

You must pass argument e in functions draw_click, draw and draw_stop, and also in function get_mouse_pos. When you pass no arguments, in function get_mouse_pos variable e is undefined.

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());