Copy a tile area in javascript canvas
I have a canvas displaying a tile map. When scrolling, rather than refreshing the entire tile list, I want开发者_JS百科 to select the useful part of the tile map that I can reuse and copy it to another canvas.
For example, if the tile map was 5 tiles across:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
And I wanted to move right (x) 1 tile... I could copy tiles 1 to 4 as these will be used in the next frame. So I would copy:
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
I seem to be having a problem coming up with the right maths for this.
At the moment I have the following code:
// Calculate from and to for x and y
// Change formula if positive or negative movement
// movX / movY = amount to move across x or y
// (i.e. movX = 1 (right) or movX = -1 (left)
// tileXFrom / tileYFrom = tile to start copy from
// tileXTo / tileYTo = tile to finish copying at
if(movX > 0)
{
tileXFrom = origX + movX;
tileXTo = tileXFrom + (tilesCountX - movX);
}
else
{
tileXFrom = origX;
tileXTo = tileXFrom + (tilesCountX + movX);
}
if(movY > 0)
{
tileYFrom = origY + movY;
tileYTo = tileYFrom + (tilesCountY - movY);
}
else
{
tileYFrom = origY;
tileYTo = tileYFrom + (tilesCountY + movY);
}
These calculations work fine however is there a better way to do them? I'm wondering if there is a way round the positive / negative if statement.
The part where I am now stuck at is what to do to get the real x, y positions for each.
So I need to convert tile 1, 0 to an on screen x, y position in order to start the copy from there.
If that all makes sense?!
Cheers
You can use ternary operators to shorten the code, but this won't change the functionality:
tileXFrom = (movX > 0) ? origX + movX : origX;
tileXTo = (movX > 0) ? tileXFrom + (tilesCountX - movX) : tileXFrom + (tilesCountX + movX);
tileYFrom = (movY > 0) ? origY + movY : origY;
tileYTo = (movY > 0) ? tileYFrom + (tilesCountY - movY) : tileYFrom + (tilesCountY + movY);
精彩评论