前提
我正在尝试将我的简单javascript画布转换为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
我猜想鼠标事件不会绑定,或者由于范围的原因它无法读取某些值。我不知道是哪一个,或者如何解决?
谢谢!
代码
以下是我的代码:
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,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,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,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,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>
)
}
}