Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript svg animation
    primarykey
    data
    text
    <p>How would I write script that would move a shape in svg linearly with javascript. I want to use requestanimframe. </p> <p>Here is an example using canvas. I just want to do the same thing except with svg.</p> <p>The script obtains a context to the canvas then it uses javascript to draw a shape with the properties of the context. Then it manages the animation of the shape on the canvas in a linear motion. I just want to use svg for the shape instead of the canvas context properties.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; body { margin: 0px; padding: 0px; } #myCanvas { border: 1px solid #9C9898; } &lt;/style&gt; &lt;script&gt; window.requestAnimFrame = (function(callback){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); }; })(); function animate(lastTime, myRectangle){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); // update var date = new Date(); var time = date.getTime(); var timeDiff = time - lastTime; var linearSpeed = 100; // pixels / second var linearDistEachFrame = linearSpeed * timeDiff / 1000; var currentX = myRectangle.x; if (currentX &lt; canvas.width - myRectangle.width - myRectangle.borderWidth / 2) { var newX = currentX + linearDistEachFrame; myRectangle.x = newX; } lastTime = time; // clear context.clearRect(0, 0, canvas.width, canvas.height); // draw context.beginPath(); context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height); context.fillStyle = "#8ED6FF"; context.fill(); context.lineWidth = myRectangle.borderWidth; context.strokeStyle = "black"; context.stroke(); // request new frame requestAnimFrame(function(){ animate(lastTime, myRectangle); }); } window.onload = function(){ var myRectangle = { x: 0, y: 50, width: 100, height: 50, borderWidth: 5 }; var date = new Date(); var time = date.getTime(); animate(time, myRectangle); }; &lt;/script&gt; &lt;/head&gt; &lt;body onmousedown="return false;"&gt; &lt;canvas id="myCanvas" width="578" height="200"&gt; &lt;/canvas&gt; &lt;/body&gt; </code></pre> <p></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload