Search code examples
html5-canvastransformimage-rotationframe-rateuint

Rotating the Uint8ClampedArray image data using a html canvas


I am currently trying to find a way to have images bouncing around the page while rotating. So far, I have succeeded in the bouncing part: The code in action. However, I am still struggling with the rotating part: The source code. I believe the problem has something to do with rotating the image data. I have have heavily researched rotating canvas data, yet the however the bug still eludes me. Could anyone shed light on this mystery.

By the way, I know that the lag could be greatly improved by preloading each image before the image is inserted onto the canvas, but I don't want to over-complicate the code until I can get the basic lay-man version to work. So now that I have examined this, please don't post about it because it's not exactly on topic.

My 2nd smaller question is this: I have observed that, in Google Chrome, when I modify the frame rate to anything other than 60 fps, then there is a MASSIVE decrease in performance: 59 fps or 60-Math.pow(2,-16) fps appears a lot slower than 60 fps. I know that it can't be because on my monitors display rate because my monitor's display rate is 59 fps, not 60 fps. So, is it because Google Chrome recognizes and optimizes 1000/60, or what? Please include a link to the documentation if possible.

EDIT

The links have been moved to the final product displayed here.


Solution

  • There is no native way to rotate a Uint8ClampedArray

    To rotate an image once it has loaded.

    // ctx is the 2D context. Image is drawn at its center point.
    function drawRotated(image,x,y,scale,rot){
       ctx.setTransform(scale,0,0,scale,x,y); // set scale and origin
       ctx.rotate(rot);
       ctx.drawImage(image, -image.width /2, -image.height / 2);
       ctx.setTransform(1,0,0,1,0,0); // restore default transformation
    }
    

    I am not at all sure what you are saying about the frame rate. A monitor with a frame rate of 59 is very unusual. As you have not shown what you are doing I will assume you are not using requestAnimationFrame

    The following will sync to the browser refresh rate.

    function mainLoop(){
        // code to render the frame   
    
        requestAnimationFrame(mainLoop);
    }
    requestAnimationFrame(mainLoop);