【发布时间】:2020-09-11 10:05:53
【问题描述】:
我一直在尝试使用 javascript 和画布中的对象在彼此正下方绘制 3 个矩形,并向它们添加一个事件侦听器。当其中一个矩形悬停在上面时,我希望这些矩形向右移动 50 像素,然后当鼠标悬停在一个矩形上时,它会移回其原始位置。
到目前为止,我已经创建了对象,声明了 eventListeners,并且已经能够获取鼠标坐标。
但是,我似乎无法在 eventListener 中调用的函数中使用对象属性。这些属性在 JavaScript 控制台中显示为未定义。我不确定如何使用我创建的矩形的属性。任何帮助将不胜感激!
// coordinates for the canvas start at the top left of the canvas object
var canvas = document.getElementById("canvas");
// get the 2D context object of the document
var ctx = canvas.getContext("2d");
class Rectangle {
constructor(xpos, ypos, width, height, color){
this.x = xpos;
this.y = ypos;
this.width = width;
this.height = height;
this.color = color;
}
draw(ctx){
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
// adding the text
ctx.fillStyle = "white";
}
mouseHoveredOn() {
let mx = event.clientX - canvas.getBoundingClientRect().left;
let my = event.clientY - canvas.getBoundingClientRect().top;
if( (mx >= this.x && mx <= (this.x + this.width) ) && (my >= this.y && my <= (this.y + this.height)) ){
for(let i = 0; i < 50; i++) {
ctx.clearRect(30+i, 150, 170, 60);
ctx.fillRect(31+i, 150, 170, 60);
}
}
}
mouseHoveredOff() {
let mx = event.clientX - canvas.getBoundingClientRect().left;
let my = event.clientY - canvas.getBoundingClientRect().top;
if( (mx <= this.x || mx >= (this.x + this.width) ) || (my <= this.y || my >= (this.y + this.height)) ) {
for(let i = 50; i > 0; i--) {
ctx.clearRect(31+i, 150, 170, 60);
ctx.fillRect(30+i, 150, 170, 60);
}
}
}
}
let rect1 = new Rectangle(30, 150, 170, 60, "rgb(200, 0, 200)");
rect1.draw(ctx);
let rect2 = new Rectangle(30, 230, 170, 60, "rgb(200, 0, 200)");
rect2.draw(ctx);
let rect3 = new Rectangle(30, 310, 170, 60, "rgb(200, 0, 200)");
rect3.draw(ctx);
canvas.addEventListener('mousemove', rect1.mouseHoveredOn, false);
canvas.addEventListener('mousemove', rect1.mouseHoveredOff, false);
【问题讨论】:
标签: javascript html css html5-canvas