我有一个 JavaScript 绘图应用程序可以在 Canvas 上绘图。下面的工具是粉笔工具。
有人可以告诉我如何在 mousedown 事件上调用该函数吗?
这是我尝试过的:
$("#drawingCanvas").mousedown(function(ev) {
tools.chalk.mousedown(ev);
});
var tools = {};
// Chalk tool.
tools.chalk = function() {
var tool = this;
this.started = false;
// Begin drawing with chalk tool.
this.mousedown = function(ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
points.push({
x: ev._x,
y: ev._y,
size: brushSize,
color: brushColor,
mode: "begin"
});
tool.started = true;
};
this.mousemove = function(ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
points.push({
x: ev._x,
y: ev._y,
size: brushSize,
color: brushColor,
mode: "draw"
});
}
};
this.mouseup = function(ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
points.push({
x: ev._x,
y: ev._y,
size: brushSize,
color: brushColor,
mode: "end"
});
img_update();
}
};
};
最佳答案
您正在从声明的函数 chalk
访问名为 mousedown
的属性,这是错误的,因为您尝试直接访问对象 chalk 上的属性
在本例中是一个声明的函数。
我认为您真正想做的是将函数 chalk
作为构造函数调用。
let tools = {};
// Chalk tool.
tools.chalk = function() {
let tool = this;
this.started = false;
// Begin drawing with chalk tool.
this.mousedown = function(ev) {
console.log("mousedown");
};
};
let chalkObj = new tools.chalk();
$("#drawingCanvas").mousedown(function(ev) {
chalkObj.mousedown(ev);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='drawingCanvas'>
<h1>CLICK ME</h1>
</div>
关于javascript - 使用 mouseevent 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57219329/