您好我正在尝试学习如何使用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());
答案 0 :(得分:3)
您必须在函数e
,draw_click
和draw
以及函数draw_stop
中传递参数get_mouse_pos
。如果不传递任何参数,则在函数get_mouse_pos
中,变量e
为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());