How to have an infinitely big canvas?

后端 未结 2 1176
野性不改
野性不改 2021-02-06 05:56

I am building a web app that uses a canvas to draw on. I would like to have an infinitly big drawing space (you can scroll as long as you want in any direction) AND save the dat

2条回答
  •  忘了有多久
    2021-02-06 06:24

    This is a bit unconventional a method, but just struck me as potentially (in theory, with unbound storage space) infinite.

    You will need to store a currently loaded chunk of the board, given as a unique ID of some sort. The chunks and their data need to be in a table with the following columns:

    • Chunk ID
    • Chunk Data
    • ID of chunk to the north
    • ID of south
    • ID of east
    • ID of west

    You need to make the canvas draggable, perhaps by using jQuery or similar (this question has some info on that).

    Now, create an event listener for the canvas to be dragged, and track the distance it moves. When released, if the canvas has not changed to a different chunk, do nothing.

    If the canvas has left the current chunk, use the stored ID to find the next chunk to load. If the ID is 0, assume the chunk does not yet exist, and create it. Otherwise, load the chunk, replacing the existing chunk. Set the canvas back to centered.

    With long enough IDs and enough storage space, this will give you an infinite canvas, as no coordinate system is used. It also allows for wrapping the edges, or creating wormholes.

    How to implement it, I'm not quite sure, but you only need to track how far the canvas has been moved. Google Maps does something similar, so I would look at how they handle it (I will do so shortly and see if I can add some implementation details to this answer).

    This may not be the most practical or simplest method, but it was fun to come up with.

    Edit: I believe this is along the lines of the basic functionality: http://candrews.net/blog/2010/10/introducing-sprymap/ It is a light-weight draggable javascript map. You simply need to track how far, then.

提交回复
热议问题