Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save itpastorn/8fb88aefb79da6e8df045cf17b037977 to your computer and use it in GitHub Desktop.
Save itpastorn/8fb88aefb79da6e8df045cf17b037977 to your computer and use it in GitHub Desktop.
Bollstuds med SVG och JavaScript RC
<h1>Bollar som studsar</h1>
<svg width="500" height="500">
<!-- Hit kommer circle via JS -->
</svg>
/* jshint esversion: 6 */
function moveBall(ball, cx, cy, xSpeed, ySpeed) {
if (cx > (svgWidth-10) || cx < 10) {
xSpeed = -xSpeed;
}
if (cy > (svgHeight-10) || cy < 10) {
ySpeed = -ySpeed;
}
cx += xSpeed;
cy += ySpeed;
ball.setAttribute("cx", cx);
ball.setAttribute("cy", cy);
setTimeout(moveBall.bind(undefined, ball, cx, cy, xSpeed, ySpeed), 20);
}
let numToCreate = 30;
let svgns = "http://www.w3.org/2000/svg";
let svg = document.getElementsByTagName("svg")[0];
let svgWidth = svg.getAttribute("width");
let svgHeight = svg.getAttribute("height");
for ( let i=0; i < numToCreate; i++ ) {
let ball = document.createElementNS(svgns, "circle");
let colorAngle = 360 * i / numToCreate;
ball.setAttribute("fill", "hsl(" + colorAngle + ", 100%, 50%)");
ball.setAttribute("r", 10);
svg.appendChild(ball);
moveBall(ball, 10+5*i, 10+5*i, Math.random()*5, Math.random()*5);
}
body {
background-color: silver;
}
h1 {
font-family: sans-serif;
text-align: center;
}
svg {
border: 2px solid;
background-color: #eee;
margin: auto;
display: block;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment