【发布时间】:2017-05-10 16:45:28
【问题描述】:
我正在尝试通过定义hover 变量、检测指定悬停区域上的鼠标事件以及(在这样做时)添加或减去此悬停变量来在 HTML 画布中编写悬停滚动功能,具体取决于悬停在哪个区域。这个hover 变量连接到一系列选择按钮的位置,就本示例而言,这些按钮包含数字 0 到 30。当这一系列选择按钮的任一端悬停在上方时,它们都会向上或向下移动就像滚动一样,但要使它像滚动一样,您必须保持鼠标移动,因为在每个新的 mousemove 事件上,画布仅是 rendered。
我的问题是如何触发mouseover 上的事件,以便if (lowerHoverBoxHitTest(x, y)) 或(upperHoverBoxHitTest(x, y))(即,如果鼠标悬停在下面脚本中定义的任一命中框上)悬停变量一直 被添加到设置的增量 (0.1) 直到鼠标离开该区域。我已经尝试用while 循环替换function mouseMove 中的if/else 语句(因为这在逻辑上类似于我所要求的)所以
while (lowerHoverBoxHitTest(x, y)) {
if (hover < 750) {
hover-=0.1;
}
}
while (upperHoverBoxHitTest(x, y)) {
if (hover > 0) {
hover+=0.1;
}
}
但这只会导致页面崩溃(可能会触发无限循环?)。除了 this 之外,Stack Overflow 上没有太多关于此的内容,但如果您的画布中有很多其他不想滚动的东西,则此解决方案没有用(除非您要绝对定义它们的位置,我不想)我在我的完整项目中做的。任何帮助将不胜感激。
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d');
var hover=0;
function upperHoverBoxHitTest(x, y) {
return (x >= 0) && (x <= 350) && (y >= 0) && (y <= 50);
}
function lowerHoverBoxHitTest(x, y) {
return (x >= 0) && (x <= 350) && (y >= 450) && (y <= 500);
}
var selectionForMenu = function(id, text, y) {
this.id = id;
this.text = text;
this.y = y;
}
selectionForMenu.prototype.makeSelection = function() {
ctx.beginPath();
ctx.fillStyle='#A84FA5';
ctx.fillRect(0, this.y+hover, 350, 30)
ctx.stroke();
ctx.font='10px Noto Sans';
ctx.fillStyle='white';
ctx.textAlign='left';
ctx.fillText(this.text, 10, this.y+hover+19);
}
var Paint = function(element) {
this.element = element;
this.shapes = [];
}
Paint.prototype.addShape = function(shape) {
this.shapes.push(shape);
}
Paint.prototype.render = function() {
ctx.clearRect(0, 0, this.element.width, this.element.height);
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].makeSelection();
}
}
var paint = new Paint(c);
for (i=0; i<30; i++) {
paint.addShape(new selectionForMenu(i+1, i, i*30));
}
paint.render();
function mouseMove(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
paint.render();
if (lowerHoverBoxHitTest(x, y)) {
hover+=1;
} else if (upperHoverBoxHitTest(x, y)) {
hover-=1;
}
}
c.addEventListener('mousemove', mouseMove);
canvas {
z-index: -1;
margin: 1em auto;
border: 1px solid black;
display: block;
background: #9F3A9B;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>uTalk Demo</title>
<link rel='stylesheet' type='text/css' href='wordpractice.css' media='screen'>
</head>
<body>
<canvas id="game" width = "350" height = "500"></canvas>
</body>
</html>
【问题讨论】:
标签: javascript html events canvas