有没有办法改进以下的html5示例,或者是浏览器 只是为了减慢处理鼠标事件? 它是一个网格,在你移动鼠标的那一刻你看到一个红色的矩形.. 但是这个矩形是一种滞后于鼠标的东西,因此移动到它的位置。 (如果鼠标移动速度很快)
这里是代码:
<body>
<canvas id="canvas" width="400" height="400">error or not supported.</canvas>
<script>
var lineSize = 10;
var rasterSize = 5;
var bx = 0;
var by = 0;
g2d = document.getElementById("canvas").getContext("2d");
g2d.setFillColor("rgb(10, 10, 10)");
g2d.fillRect(0, 0, g2d.canvas.width, g2d.canvas.height);
g2d.setStrokeColor("rgb(0, 0, 255)");
g2d.setLineWidth(lineSize);
function repaint(){
g2d.clearRect(0, 0, g2d.canvas.width, g2d.canvas.height);
g2d.beginPath();
for(i = 0; i < rasterSize + 1; i++){
g2d.moveTo(0, (lineSize / 2) + i * (g2d.canvas.height - lineSize) / (rasterSize));
g2d.lineTo(g2d.canvas.width, (lineSize / 2) + i * (g2d.canvas.height - lineSize) / (rasterSize));
g2d.moveTo((lineSize / 2) + i * (g2d.canvas.width - lineSize) / (rasterSize), 0);
g2d.lineTo((lineSize / 2) + i * (g2d.canvas.width - lineSize) / (rasterSize), g2d.canvas.height);
}
g2d.stroke();
g2d.setFillColor("red");
g2d.fillRect(bx - 5, by - 5, 11, 11);
}
repaint();
g2d.canvas.addEventListener("mousemove", function(e){
bx = e.offsetX;
by = e.offsetY;
repaint();
});
</script>
</body>
body {
margin: 0;
width: 100%;
height: 100%;
display: block;
background: black;
}
canvas {
margin: auto;
margin-top: 50px;
display: block;
}
答案 0 :(得分:0)
您可以将鼠标事件与图形分开以提高性能。
好处是:
答案 1 :(得分:-1)
你可以像我在这里一样限制重画率:
http://jsfiddle.net/sh6o91g4/1/
根据您的需要进行调整,因为它会固定性能,但也会降低渲染质量(跳帧会有缺点)
var now = new Date().getTime();
if(now - time > 10){
time = now;
bx = e.offsetX;
by = e.offsetY;
repaint();
}