gpt4 book ai didi

javascript - 将对象函数传递给事件监听器 javascript

转载 作者:行者123 更新时间:2023-11-28 06:22:59 25 4
gpt4 key购买 nike

我正在尝试将成员函数附加到 Canvas eventListsner。看来是吸收不了了。下面是 html 代码的片段。我确实想将我的事件关联到特定对象,并且不希望它是静态的。

<!DOCTYPE html>
<html>
<body>
<p>Graph</p>
<canvas id="canvasGraph" width="600" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</br>
<p><button onclick="main()">Try it</button></p>

<script>
"use strict";

var cg;

function main()
{
var canvasElement = document.getElementById("canvasGraph");
cg = new CanvasClass(100, canvasElement);
//alert(cg.test);
cg.addGraphListener();
}

class CanvasClass
{

constructor(_testInt, _canvasElement)
{
this.test = _testInt;
this.canvasElement = _canvasElement;
}

getMousePos(evt)
{
var canvas = this.canvasElement;
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}

writeMessage(message) {
var canvas = this.canvasElement;
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 10, 25);
}

addGraphListener()
{
//alert(this.test);
this.canvasElement.addEventListener('click', this.testfunc, false); // Not as expected
this.canvasElement.addEventListener('click', this.listener, false);
this.canvasElement.addEventListener('click', CanvasClass.staticTest, false);
}

static staticTest()
{
alert(cg.test); // works but clumsy
}

testfunc()
{
alert(this.test); // object is not recognized
}

listener(evt)
{
//var mousePos = this.getMousePos(evt); // Uncaught TypeError: this.getMousePos is not a function
var mousePos = getMousePos(evt); // Uncaught ReferenceError: getMousePos is not defined
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
this.writeMessage(message);
}
}

</script>

最佳答案

试试这个

CanvasClass.protype.addGraphListener = function()
{
var tfunc = this.listener;
this.canvasElement.addEventListener('click', function(event){

tfunc (evt);

}, false);
}

CanvasClass.protype.listener = function(evt)
{
var mousePos = this.getMousePos(evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
this.writeMessage(message);
}

CanvasClass.protype.getMousePos= function(evt)
{
var canvas = this.canvasElement;
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}

关于javascript - 将对象函数传递给事件监听器 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356613/

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