Learn Create Your Own Split Screen

Next Page

Now the magic happens.

In Do_a_Frame, we simply call translate.

function Do_a_Frame () { ctx.clearRect(0, 0, myCanvas.width, myCanvas.height); ctx.save(); ctx.translate(viewport_offset_x, viewport_offset_y); handle_keys_that_are_pressed(); for (var i=0; i < obstacles.length; i++) obstacles[i].Do_Frame_Things(); for (var i=0; i < fruit.length; i++) { fruit[i].Do_Frame_Things(); if (ImagesTouching(fruit[i], hero, 10)) make_bad_thing_happen_to_fruit(fruit[i]); } hero.Do_Frame_Things(); ctx.restore(); }

Recall that changes to the drawing context are cumulative, so we also save the context before we translate, and when we're done doing the drawing, we restore the context so the effect of the translate are removed.


Note that we do the clearRect before the translation is applied. Why? Because we always want to clear the visible portion of the canvas, before any viewport is applied. Everything else moves with the viewport, but not the clearing of the bit we can see.