Canvas, shape animation along a square path using a sine wave

I am trying to make a simple shape an animation along a square path based on the radius set. Atm I use a sine wave to establish my position over time, so it basically animates in a circular path. Is there a way to use math to change a sine wave to make a square animation. I know there are other ways to do this, but I would be interested to know the math behind it.

I have an example script:

t = new Date().getTime()

r = 25

x = (r * Math.cos t * 0.005) 
y = (r * Math.sin t * 0.005)

http://jsfiddle.net/Z5hrM/1/

+4
source share
3 answers

, ! D:

 x = (r^D * cos(theta))^(1/D) and y = (r^D * sin(theta))^(1/D)

D = 1, , . D = 0,5, , D < 0.5 . D > 1, , D → . ; D .

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>animation problem</title>
<script type='text/javascript'>
    function demo(){
        var w = 400;
        var ctx = document.getElementById("canvas").getContext("2d");
        ctx.canvas.width = w;
        ctx.canvas.height = w;
        var r = w/4;
        var theta = 0;

        setInterval(function(){
            ctx.canvas.width += 0;    //  clear the canvas
            ctx.translate(w/2, w/2);  //  center it on (0,0)
            var D = +document.getElementById("exponent").value;

            var xSign = Math.cos(theta) < 0 ? -1 : 1;  // Handle all quadrants this way
            var ySign = Math.sin(theta) < 0 ? -1 : 1;
            var x = xSign*Math.pow( Math.pow(r, D)*Math.abs(Math.cos(theta)), 1/D );
            var y = ySign*Math.pow( Math.pow(r, D)*Math.abs(Math.sin(theta)), 1/D );
            ctx.fillStyle = "blue";
            ctx.arc( x, y, 20, 0, 6.2832, false );
            ctx.fill();

            theta += Math.PI/100;
        }, 20);
    }
</script>
</head>
<body onload='demo()'>
    <input id='exponent' type=text value='1'\>
    <br />
    <canvas id='canvas'></canvas>
</body>
</html>
+1

jsFiddle Demo

. , x, sin y, , .

Math.cos t Math.sin t

xcos = Math.cos t * 0.005
ysin = Math.sin t * 0.005

if Math.abs(xcos) > Math.abs(ysin)
 xcos = Math.round(xcos)                                       
else
 ysin = Math.round(ysin)     

x = @cx + (radius * xcos)
y = @cy + (radius * ysin)
0

Your r variable should be the vector of two positions (x, y) that will handle the position / increment by x and y respectively. See when you do it. X = (0 * Math.cos t * 0.005). The circus can simply be moved down. To get the behavior of the form, you need to control the vector (positions x and y) over time and use the remainder to wrap the positions x and y (%).

Sincerely.

0
source

Source: https://habr.com/ru/post/1543584/


All Articles