const ctx = canvas.getContext('2d');
canvas.height = 200;
canvas.width = 600;
const tileSize = canvas.height/6;
const MAIN = {position:{x: 120, y: 120}};
const canvasRefresh = {x: 0, y: 20};
document.body.onmousemove = e => MAIN.position = {x: e.clientX, y: e.clientY};
const tiles = {x: 20, y: 20}
function update(){
moveMap();
requestAnimationFrame(update);
}
function drawMap(){
for(var i = 0; i < tiles.x; i++){
for(var j = 0; j < tiles.y; j++){
ctx.fillStyle = ['black', 'green','orange'][Math.floor((i+j+canvasRefresh.x1+canvasRefresh.y1)%3)];
ctx.fillRect(tileSize * i, tileSize * j, tileSize, tileSize);
}
}
}
function moveMap(){
const sector = {
x: Math.round(-MAIN.position.x % tileSize),
y: Math.round(-MAIN.position.y % tileSize)
};
const x2 = Math.floor(MAIN.position.x/tileSize);
const y2 = Math.floor(MAIN.position.y/tileSize);
if(canvasRefresh.x1 != x2 || canvasRefresh.y1 != y2){
canvasRefresh.x1 = x2;
canvasRefresh.y1 = y2;
requestAnimationFrame(drawMap);
}
$('#canvas').css({
transform: "translate3d(" + sector.x + "px, " + sector.y + "px, 0)"
});
}
update();
canvas {
transition: all 1500ms cubic-bezier(0.250, 0.100, 0.250, 1.000);
transition-timing-function: cubic-bezier(0.250, 0.100, 0.250, 1.000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id=canvas></canvas>
requestAnimationFrame(drawMap)
中使用似乎很奇怪 - 因为你已经在 RAF 回调中了,所以只需调用drawMap()
而不是触发一个单独的回调。 - ggorlen