JSFiddle - React, Tailwind, and code Playground
by tara5
HTML
<svg id="player" version="1.1" id="orange-legs" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="500px" height="500px" xml:space="preserve">
<rect id="body" x="70"
width="100" height="150"
rx="15" ry="15"/>
<path id="rightLeg" d="M100,130 C100,130 120,130 120,150 L120,250 C120,250 120,280 150,280" stroke="black"
stroke-width="3" fill="none"/>
<path id="leftLeg" d="M100,130 C100,130 120,130 120,150 L120,260 C120,260 120,280 150,280" stroke="black"
stroke-width="3" fill="none"/>
</svg>
CSS
body {
overflow: hidden;
}
#rightLeg {
animation: rightStep 1s linear infinite;
animation-play-state: paused;
transform: rotate(-15deg);
transform-origin: 25% 25%;
}
#leftLeg {
animation: leftStep 1s linear infinite;
animation-play-state: paused;
transform: rotate(15deg);
transform-origin: 25% 25%;
}
@keyframes leftStep {
25% {
transform: rotate(0deg);
}
50% {
transform: rotate(-15deg);
}
75% {
transform: rotate(0deg);
}
100% {
transform: rotate(15deg);
}
}
@keyframes rightStep {
25% {
transform: rotate(0deg);
}
50% {
transform: rotate(15deg);
}
75% {
transform: rotate(0deg);
}
100% {
transform: rotate(-15deg);
}
}
JavaScript
var player = document.getElementById("player"),
leftLeg = document.getElementById("leftLeg"),
rightLeg = document.getElementById("rightLeg"),
legsMarginLeft = 0,
speed = 60,
dt = 1/60 * 1000,
right = false,
left = false;
var animationPlayStateProperty = "animationPlayState",
animationPlayStateRunning = "running",
animationPlayStatePaused = "paused",
rightLegStyle = rightLeg.style,
leftLegStyle = leftLeg.style,
playerStyle = player.style;
var start = Date.now();
function step() {
var now = Date.now();
var progress = now - start;
if (right) {
legsMarginLeft += progress/dt * speed;
}
if (left) {
legsMarginLeft -= progress/dt * speed;
}
if (right || left) {
playerStyle.marginLeft = legsMarginLeft;
rightLegStyle[animationPlayStateProperty] = animationPlayStateRunning;
leftLegStyle[animationPlayStateProperty] = animationPlayStateRunning;
} else {
rightLegStyle[animationPlayStateProperty] = animationPlayStatePaused;
leftLegStyle[animationPlayStateProperty] = animationPlayStatePaused;
}
start = now;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
document.body.addEventListener("keyup", function(event) {
if (event.which === 39) {
right = false;
}
if (event.which === 37) {
left = false;
}
});
document.body.addEventListener("keydown", function(event) {
if (event.which === 39) {
right = true;
}
if (event.which === 37) {
if (legsMarginLeft >= speed) {
left = true;
}
}
});