lundi 9 janvier 2023

Object moving between random positions, how to put speed limitation with CSS or Javascript?

I have a keyframe animation in css like this:

@keyframes anim-target1 {
    0% {
    scale: 0.24;
        transform: translateX(0) translateY(0);
    }

    100% {
        scale: 0.24;
        transform: translateX(-650px) translateY(-25px);
    }
}

Now I want to make the object go forth and back randomly in between these two points, stopping at random positions not having to go to the start or end before going the other way. And having it be random every time it is run, otherwise I would obviously just make the keyframes for it. The keyframes being like a path it can not deviate from. Is there a way to do this simple with css and javascript? Taking scale into consideration, should it be two points between different scales also (I only have for X and Y). Anyone up for the task to solve?

I have tried making a script that creates random keyframes in between 0 and 100, and it works, but the speed is not consistent but fluxate. Somehow to make a speed limit on how fast the object can move no matter how far or short it travels.

Here is the javascript I have so far to make the random positions:

// Generate a random number of intermediate positions
    var numPositions = Math.floor(Math.random() * 10) + 1;

    // Generate the keyframes string
    var keyframes = "@keyframes anim-target1 {\n";
    keyframes += "  0% { scale: 0.24; transform: translateX(0) translateY(0); }\n";
    for (var i = 1; i <= numPositions; i++) {
        // Generate random values for the translateX and translateY properties
        var translateX = Math.floor(Math.random() * 651);
        var translateY = Math.floor(Math.random() * 26);
        keyframes += "  " + (i * 10) + "% { scale: 0.24; transform: translateX(" + translateX + "px) translateY(" + translateY + "px); }\n";
    }
    keyframes += "  100% { scale: 0.24; transform: translateX(-650px) translateY(-25px); }\n";
    keyframes += "}";

    // Inject the keyframes string into the page
    var style = document.createElement("style");
    style.innerHTML = keyframes;
    document.head.appendChild(style);

I figure it would be better maybe to make all the animation points in javascript somehow might be better, if anyone has any suggestions?

I was expecting this solution I have could be somehow easily controled to have a speed limit and not determin by the animation time. But yet to figure it out.




Aucun commentaire:

Enregistrer un commentaire