因此,我试图将动态HTML canvas元素集成到React JS组件中,但我希望它具有事件侦听器。我的最终目标是使用单击事件侦听器来实现它,但是现在我只用鼠标移动一个就遇到了麻烦(我将代码像HTML一样用内联Javascript剥离了下来,我想弄清楚如何甚至可以将其重构为可在React组件中使用。
据我所知,代码说在componentDidMount方法中未定义getMousePos和writeMessage。重构此代码的帮助将不胜感激。单击示例非常令人难以置信,但老实说,只要有鼠标移动事件侦听器的帮助,我就会很高兴。
感谢您提供的任何帮助。
import React, { Component } from 'react';
class Canvas extends Component {
render () {
return (
<canvas id="myCanvas" width="578" height="200"></canvas>
);
}
componentDidMount() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function (evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
}
writeMessage = (canvas, message) => {
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);
}
getMousePos = (canvas, evt) => {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
}
export default Canvas;