HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Resize renderer on browser window size change

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
resizesizebrowserwindowrendererchange

Problem

For a game, there is some WebGLRenderer object that wraps around canvas element. There is need to update it's size when browser window size changes. Here goes my current code written using BaconJS. What do you think about it ? Would you improve it in any way or maybe do it other way? I have read that listening to resize event is just slow for game purposes.

# Make the property of window object 
rWindow = Bacon.constant window

# Sample window by tick event
sTickWindow = rWindow.sampledBy app.land.stream('tick')

# Look for width and height changes on every tick
sWidth = sTickWindow.map('.innerWidth').skipDuplicates()
sHeight = sTickWindow.map('.innerHeight').skipDuplicates()
sSize = Bacon.combineAsArray sWidth, sHeight

# Resize renderer when size is changed
Bacon.onValues rRenderer, sSize, (renderer, size) ->
    # Apply size update to renderer
    renderer.setSize size...


Note that app.land.stream('tick') is basically EventStream of requestAnimationFrame invocations.

Update

To make the understanding easier, I have made fiddle for it. Open dev console and try to resize the Result window rather then browser window.

Solution

I think your code style is fine. If you are happy with this method, I think you've written it pretty well.

As potential upgrades, here are two alternative methods that better obey the Rules of Clarity and Simplicity.

First, is there a reason you're using so much machinery to get the window size? This would be clearer with fewer moving parts. Anyone coming to your codebase knowing only JavaScript/CoffeeScript will understand what is happening here:

# setup canvas
canvas = document.createElement 'canvas'
document.body.appendChild canvas

# update ui every frame
tick = ->
resize()
requestAnimationFrame tick
requestAnimationFrame tick

resize = ->
# only resize canvas if necessary
canvas.width = window.innerWidth if canvas.width isnt window.innerWidth
canvas.height = window.innerHeight if canvas.height isnt window.innerHeight


There's a fiddle of this here.

You could also employ modules that throttle redraws and polyfill requestAnimationFrame
like this example. I would argue that this method would also be clearer for a newcomer to your codebase.

raf = require 'raf' # requestAnimationFrame polyfill
throttle = require 'lodash.throttle'

# only redraw every 200 milliseconds
raf().on 'data', throttle(resize, 200)


See it in action (as JavaScript) on RequireBin here.

Context

StackExchange Code Review Q#51967, answer score: 3

Revisions (0)

No revisions yet.