Created
September 3, 2013 09:56
-
-
Save stephen-james/6421895 to your computer and use it in GitHub Desktop.
resize svg using debouncing and an event stack to render at a maximum of 60hz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> | |
<script> | |
// set refresh rate to 60hz | |
var refreshRate = 1000 / 60, | |
debounceThreshold = 500, | |
resizeEventStack = [], | |
debouncedResizeTimeoutId; | |
// ensure that at most, we will attempt to process events at 60hz, | |
// an acceptable visual rendering frequency | |
setInterval(function() { | |
processNextEventOnStack() | |
}, | |
refreshRate | |
); | |
// capture window resize events | |
$(window).resize(function() { | |
// ensure there is only one resize event on the stack at any time | |
resizeEventStack.pop(); | |
resizeEventStack.push(resize); | |
// debounce the resize event so that only the last call to window resize ever gets | |
// called by setTimeout | |
clearTimeout(debouncedResizeTimeoutId); | |
// debounce threshold must be sufficient to not be mistaken as gaps between real successive window resize events | |
debouncedResizeTimeoutId = setTimeout(finalResize, debounceThreshold); | |
}); | |
// pop the next event and process it | |
function processNextEventOnStack() { | |
var resizeEventToCall = resizeEventStack.pop(); | |
if (resizeEventToCall) { | |
resizeEventToCall(); | |
} | |
} | |
// the utility resize that happens according to our refresh frequency | |
function resize() { | |
var desiredWidth = 1024, | |
actualWidth = $(window).width(), | |
zoomRatioRounded = Math.round(actualWidth / desiredWidth * 1000) / 1000; | |
$("#drawArea").css("zoom", zoomRatioRounded); | |
} | |
// the thorough resize that happens on the last event | |
function finalResize() { | |
// filling the rect with a different colour here to illustrate final/thorough resize has taken place | |
$("#drawArea rect").css("fill", getRandomColor()); | |
} | |
function getRandomColor() { | |
var letters = '0123456789ABCDEF'.split(''), | |
color = '#'; | |
for (var i = 0; i < 6; i++ ) { | |
color += letters[Math.round(Math.random() * 15)]; | |
} | |
return color; | |
} | |
</script> | |
</head> | |
<body> | |
<svg id="drawArea" width="800px" height="100px"> | |
<rect x = "0" y = "0" width = "800" height = "100" fill = "yellow" stroke = "black" stroke-width = "3"/> | |
</svg> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment