我正在 Canvas 上绘制一些对象(例如矩形)。它也有背景图像。
但是当我使用鼠标事件绘制矩形时,屏幕闪烁很多。 当我改变对象的位置时,如何停止鼠标移动/鼠标按下时的闪烁,以便一次又一次地重新绘制 Canvas 。 我们可以渲染它一段时间或有任何其他解决方案吗?
我听说 java 和 C# 中有一些“Redraw = false”函数,但我的代码是 JavaScript 中的。
http://jsfiddle.net/G6tLn/7/ `函数 myMove(e) { if (isDrag) { getMouse(e);
mySel.x = mx - offsetx;
mySel.y = my - offsety;
// something is changing position so we better invalidate the canvas!
invalidate();
} else if (isResizeDrag) {
// time ro resize!
var oldx = mySel.x;
var oldy = mySel.y;
// 0 1 2
// 3 4
// 5 6 7
switch (expectResize) {
case 0:
mySel.x = mx;
mySel.y = my;
mySel.w += oldx - mx;
mySel.h += oldy - my;
break;
case 1:
mySel.y = my;
mySel.h += oldy - my;
break;
case 2:
mySel.y = my;
mySel.w = mx - oldx;
mySel.h += oldy - my;
break;
case 3:
mySel.x = mx;
mySel.w += oldx - mx;
break;
case 4:
mySel.w = mx - oldx;
break;
case 5:
mySel.x = mx;
mySel.w += oldx - mx;
mySel.h = my - oldy;
break;
case 6:
mySel.h = my - oldy;
break;
case 7:
mySel.w = mx - oldx;
mySel.h = my - oldy;
break;
}
invalidate();
}
getMouse(e);
// if there's a selection see if we grabbed one of the selection handles
if (mySel !== null && !isResizeDrag) {
for (var i = 0; i < 8; i++) {
// 0 1 2
// 3 4
// 5 6 7
var cur = selectionHandles[i];
// we dont need to use the ghost context because
// selection handles will always be rectangles
if (mx >= cur.x && mx <= cur.x + mySelBoxSize &&
my >= cur.y && my <= cur.y + mySelBoxSize) {
// we found one!
expectResize = i;
invalidate();
switch (i) {
case 0:
this.style.cursor = 'nw-resize';
break;
case 1:
this.style.cursor = 'n-resize';
break;
case 2:
this.style.cursor = 'ne-resize';
break;
case 3:
this.style.cursor = 'w-resize';
break;
case 4:
this.style.cursor = 'e-resize';
break;
case 5:
this.style.cursor = 'sw-resize';
break;
case 6:
this.style.cursor = 's-resize';
break;
case 7:
this.style.cursor = 'se-resize';
break;
}
return;
}
}
// not over a selection box, return to normal
isResizeDrag = false;
expectResize = -1;
this.style.cursor = 'auto';
}
}
`
最佳答案
500 多行...需要诊断很多!
快速浏览该代码后的一些想法:
创建矩形或调整其大小时,使用覆盖在结果 Canvas 顶部的单独编辑 Canvas 。这样,唯一被重绘的是您正在处理的矩形,而不是之前的每个矩形。创建/调整大小完成后,将覆盖 Canvas 绘制到显示 Canvas 上。
使用 requestAnimationFrame 而不是 setInterval 来进行定时重绘。 R.A.F 将其重绘与显示器的刷新周期同步,以获得更好的性能。
不要使用单独的调整器。管理单独的调整器需要大量计算时间。相反,执行其他操作并让用户拖动调整形状边框的大小。
关于javascript - 当鼠标移动到对象上时发生闪烁 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23067497/