HTML and CSS Reference
In-Depth Information
You can try it yourself to see how much time it'd take your computer to render an image that big. The example in
Listing 8-24 loads a massive image and attempts to paint it on the canvas every 33.33 ms.
Listing 8-24. Painting a Large Image
;(function() {
var fps = 30, // Define the maximum number of FPS
interval = 1000 / fps, // Calculate the interval in milliseconds
delta = 0, // Variable initialisation
previousTs = 0; // Variable initialisation
shouldRepaint = true, // Set the repaint flag to true by default
viewportWidth = 640, // Setup the width of the viewport (the canvas)
viewportHeight = 480, // Setup the height of the viewport (the canvas)
canvas = document.querySelector('canvas'), // Grab a reference to the canvas object...
ctx = canvas.getContext('2d'), // ...and its context
backgroundTexture = new Image(); // Declare a new image object that we'll be using to store
our background texture
// Set the default size of the canvas (it will be resized when the background image is loaded)
canvas.width = viewportWidth;
canvas.height = viewportHeight;
// Load the background texture
backgroundTexture.src = 'texture.jpg';
backgroundTexture.addEventListener('load', function() {
// Resize the canvas to the size of the image
canvas.width = backgroundTexture.width;
canvas.height = backgroundTexture.height;
// Call requestAnimationFrame as soon as we make sure the image is loaded
requestAnimationFrame(update);
}, false);
function update(ts) {
// Calculate the delta between the previous timestamp and the new one
delta = ts - previousTs;
// Performing a calculation here means that it will be
// executed every 16.67 ms. at 60 frames per second
// Check whether or not something needs to be repainted in the scene
// Only execute the paint routine if the delta is bigger
// than the interval and the shouldRepaint flag is set to true
if (delta > interval && shouldRepaint) {
 
Search WWH ::




Custom Search