Kyryll Tenin Baum
Kyryll Tenin Baum

Reputation: 132

HTML5 Canvas Layers Conundrum (z-index)

I'm working on a site where among other things there are three layers of visuals:

  1. Layer 1 - divs with laid out textual info that scroll vertically
  2. Layer 2 - footer image that is fixed at the bottom of the view port (30% height)
  3. Layer 3 - canvas animation layer that is fixed full screen

Conundrum:

I understand that in real world if these were the physical paper cut-outs it would be impossible to achieve this. Is there a feasible way to achieve this programatically in a website?

Edit: I see I provoked answers that are design related. Rightfully so:) I will wireframe it to show here. For now I will explain it a bit more:

The footer image is my city's sky line. The canvas animation is used to render birds flying over the whole screen area. The textual information (and background divs) should be scrolling down behind the city sky line. But I don't want the flying birds to hover over the text on the screen :)

Is there a way to make canvas transparent only for one other element (text)?

Upvotes: 0

Views: 820

Answers (2)

Hylianpuffball
Hylianpuffball

Reputation: 1561

I think I get what you're saying. One possibility is to split your animation onto multiple <canvas> elements, each with their own position and z-index based on where they are on the screen (so at the bottom over the footer, you'd have z-index 0, and then halfway or so up the page you'd have another canvas with z-index -5 or such.) Absolute positioning/JavaScript assistance would be the easiest way to size and place everything properly, though it's not the only option.

The canvas 2d api actually makes this quite easy to do, too... no change to your drawing logic needed at all! Just transform the context of any canvas that isn't exactly aligned with the top left, and draw the scene in all canvases as normal. For example, just before you draw, run

context.save();
//Determine canvas pixel position, possibly with jQuery
context.translate(-myCanvasXPosition, -myCanvasYPosition);

...//draw

context.restore();

This will adjust your scene so that the point (0,0) is always the upper-left corner of the browser for all your canvases (instead of the usual upper-left corner of each canvas), so all your drawing logic will draw the correct thing no matter which canvas it's in. If performance starts to be a problem, you could add logic to only try to draw elements that may actually be shown in the canvas currently drawing.

With this method, what appears to be a single background drawing will actually be multiple drawings stitched together invisibly, which will let you make different parts of the drawings different z-indexes.

Upvotes: 2

you could change the z-index depending on the position

Upvotes: 1

Related Questions