K
K
kamlauka2018-07-25 13:41:15
JavaScript
kamlauka, 2018-07-25 13:41:15

How to correctly set the animation of a small rotation-"wiggle" in the canvas?

How to make the cloud not rotate 360 ​​degrees, but just sway a little?
https://codepen.io/kamlauka/pen/oMwqNZ

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-07-25
@kamlauka

You can make the rotation angle a function of the sine of the elapsed time. More or less like this:

var ts0;
function draw(ts) {
    // ...
    if(!ts0) ts0 = ts;
    const dt = ts - ts0; // сколько прошло миллисекунд
    //  ...
    ctx.translate(500, 180 + Math.sin(dt/352)*3); 
    ctx.rotate( Math.sin(dt/630) / 40 );
Here, in addition to turning, it also sways slightly vertically. Also, a smooth sinusoid, but with a different period so that it does not look cyclical.
Working example .
The current time is passed to the function called by the requestAnimationFrame()parameter, so you can not bother with creating a new Date object, but use this parameter.
From the ratio of the coordinates in ctx.drawImage(cloud, -350, -250);with the size of the picture, the center is determined, relative to which the rotation will be obtained. It is desirable to choose it so that they fall on the visual center of mass of the cloud.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question