Search code examples
gridlinecreatejseaseljs

Drawing a grid efficiently with EaselJS StageGL


I would like to draw a grid on a canvas using EaselJS. I am using the new WebGL stage, StageGL.

A grid is basically N times of a horizontal line and M times of a vertical line.

I see multiple options:

  1. Draw N+M lines as all different shapes (I am talking about EaselJS "Shape" instances), cache them (as WebGL needs rasters) and add them to the stage.
  2. Draw 1 horizontal and 1 vertical line, cache them (as WebGL needs rasters) and somehow draw the same image in the stage
  3. Draw a single shape which consists of N+M paths, cache it and add it to the stage.

Option #1 seems naive to me. They're all the same image, why drawing them to the cache N+M times?

Option #2 would solve the problem in option #1, but I don't know how to do it.

Option #3 results in a very large image. For N=50, M=50 and gridSpacing=50px, it would result in a 2500x2500 px image. I don't know if this is ideal.

Which one is the best approach?

Are there any other approaches? I don't think I am the first person who draws a grid :)


Solution

  • You can pretty easily cache a shape, and use the resulting cache (canvas) as the source for a Bitmap.

    var shape = new createjs.Shape();
    shape.graphics.drawStuff();
    
    // Since shapes have no bounds, you will have to know the bounds based on what you draw:
    shape.cache(x, y, w, h);
    
    var bmp = new createjs.Bitmap(shape.cacheCanvas);
    

    You can draw as many of these Bitmaps without any additional cost, since its the same source canvas/image. EaselJS StageGL (latest NEXT, released shortly hopefully) renders this in WebGL no problem.

    Check out the SpriteSheetBuilder demo and docs in GitHub to draw content to a SpriteSheet/Sprite instead of a Bitmap.

    Cheers.