gpt4 book ai didi

javascript - 无法使用 jquery 读取未定义的属性 'clientX'

转载 作者:行者123 更新时间:2023-11-30 11:54:34 24 4
gpt4 key购买 nike

您好,我正在尝试学习如何使用 HTML5 canvas 制作绘图应用程序到目前为止我写了这段代码,问题是浏览器控制台一直告诉我无法读取未定义的属性“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());

最佳答案

您必须在函数 draw_clickdrawdraw_stop 以及函数 中传递参数 e >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());

关于javascript - 无法使用 jquery 读取未定义的属性 'clientX',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38407239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com