Javascript JS:从按钮调用函数
我正在学习纯JavaScript。我的问题很基本,我希望有人能给我指出正确的方向。在画布绘制练习中,我使用以下功能:Javascript JS:从按钮调用函数,javascript,html,function,button,Javascript,Html,Function,Button,我正在学习纯JavaScript。我的问题很基本,我希望有人能给我指出正确的方向。在画布绘制练习中,我使用以下功能: drawingTools.pencil = function () { document.getElementById("activeTool").value = "Pencil"; this.mousedown = function (evt) { isDrawing = true; startX = getendY(tmp_c
drawingTools.pencil = function () {
document.getElementById("activeTool").value = "Pencil";
this.mousedown = function (evt) {
isDrawing = true;
startX = getendY(tmp_canvas, evt);
};
this.mousemove = function (evt) {
compositeDraw()
endY = getendY(tmp_canvas, evt);
if (isDrawing) {
tmp_context.beginPath();
tmp_context.moveTo(startX.x, startX.y);
tmp_context.lineTo(endY.x, endY.y);
tmp_context.lineJoin = 'round';
tmp_context.lineCap = "round";
tmp_context.stroke();
tmp_context.strokeStyle = defaultLineColor;
tmp_context.lineWidth = defaultLineThickness;
}
startX = endY;
};
this.mouseup = function (evt) {
isDrawing = false;
drawtmp_contextOncanvas();
}
};
使用以下行,此函数可以正常工作:
pencil.addEventListener('click', this.changeDrawingTool, false);
当我尝试使用如下按钮图标调用drawingTools.pencil
函数时:
document.getElementById("iconPencil").addEventListener('click', drawingTools.pencil, false);
上述功能不会触发
演示:
在第二个选项中
document.getElementById("iconPencil").addEventListener('click', drawingTools.pencil, false);
此
指向#iconPencil
元素。此元素不实现像mousedown
,mousemove
为避免丢失此
,您可以使用绑定
document.getElementById("iconPencil").addEventListener('click', drawingTools.pencil.bind(pencil), false);
您能否共享您的JSFIDLE或jsbin链接
changeDrawingTool
是全局方法?您能通过窗口运行它吗?changeDrawingTool
<代码>铅笔变量指向什么?谢谢你的回复。这是jsfiddle:你确定drawingTools
是他试图绘制的画布吗?看看该方法中的this
的作用:this.onmousemove
等。我认为他需要将其绑定到画布上。感谢您的回复。不幸的是,建议的解决方案对我不起作用。我将用完整的源代码编辑上述问题。感谢Krzysztof Safjanowski为我指出绑定方向:document.getElementById(“iconPencil”).addEventListener('click',changeDrawingTool.bind(pencil),false)代码>并且代码工作得很好。