前提
我正在尝试将简单的 javascript Canvas 转换为 React.js 代码。我在 React.js 中设置鼠标单击和鼠标移动事件时遇到问题。
错误
我得到了
Uncaught TypeError: Cannot read property 'offsetLeft' of undefined
at HTMLCanvasElement.click_buildings
TypeError: Cannot read property 'offsetLeft' of undefined
HTMLCanvasElement.onMouseMove
我猜要么是鼠标事件没有绑定(bind),要么是因为范围原因它无法读取某些值。我不知道是哪一个,或者如何解决?
提前致谢!
代码
下面是我的代码:
class Economy extends React.Component {
componentDidMount() {
this.updateCanvas();
let source = null;
}
updateCanvas() {
const canvas = this.refs.gameScreen;
let ctx = canvas.getContext("2d");
const canvas_buildings = this.refs.buildings;
const ctx_buildings = canvas_buildings.getContext("2d");
canvas.addEventListener("mousemove", this.onMouseMove, false);
canvas.addEventListener("click", this.click, false);
canvas_buildings.addEventListener("click", this.click_buildings, false);
let assigned_cordinates = [];
var img = new Image();
var img_copper = new Image();
img_copper.src = Copper;
img_copper.onload = function() {
ctx_buildings.drawImage(img_copper, 0, 0, 90, 120);
}
onMouseMove(e) {
var x = e.clientX - this.canvas.offsetLeft;
var y = e.clientY - this.canvas.offsetTop;
var x_cord = Math.trunc(x / 90);
var y_cord = Math.trunc(y / 120);
if (this.assigned_cordinates.indexOf(this.old_x + "" + this.old_y) === -1) {
this.ctx.clearRect(this.old_x * 90, this.old_y * 120, 90, 120);
}
if (this.assigned_cordinates.indexOf(x_cord + "" + y_cord) === -1) {
if (this.source === "copper") {
this.ctx.drawImage(this.img_copper, x_cord * 90, y_cord * 120, 90, 120);
} else if (this.source === "none") {
}
}
this.old_x = x_cord;
this.old_y = y_cord;
}
click(e) {
console.log(this.assigned_cordinates);
var x = e.clientX - this.canvas.offsetLeft;
var y = e.clientY - this.canvas.offsetTop;
var x_cord = Math.trunc(x / 90);
var y_cord = Math.trunc(y / 120);
if (this.assigned_cordinates.indexOf(x_cord + "" + y_cord) === -1) {
if (this.source === "copper") {
this.ctx.drawImage(this.img_copper, x_cord * 90, y_cord * 120, 90, 120);
this.assigned_cordinates.push(x_cord + "" + y_cord);
} else if (this.source === "none") {
}
}
}
click_buildings(e) {
var x = e.clientX - this.canvas_buildings.offsetLeft;
var x_cord_buildings = Math.trunc(x / 90);
if (x_cord_buildings === 0) {
this.source = "copper";
}
}
render() {
return(
<div className="screens">
<canvas ref="buildings" className="buildings" width={800} height={100}/>
<canvas ref="gameScreen" className="gameScreen" width={800} height={600}/>
</div>
)
}
}
最佳答案
错误意味着this.canvas
未在您尝试从中访问它的范围 中定义。我假设这个 const canvas = this.refs.gameScreen;
是您尝试访问的 Canvas 。如果这是真的,那么它会提示 undefined 因为它只存在于 updateCanvas() {...}
中。并且您正在尝试从外部访问它 updateCanvas()
您需要在整个组件都可以访问的地方定义 Canvas 。也许在 props 之类的东西中,我对 react 不熟悉,所以我不知道组件数据的确切定义位置。在 Vue 中,它会在数据中。
关于javascript - mouseclick 和 mousemove 事件在 react Canvas 中给出偏移错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58703149/