Last active
April 28, 2018 16:13
-
-
Save jarrettmeyer/cb4bcd3faf63e6def08262994a7dfa5e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define our constants | |
const width = 600; | |
const height = 400; | |
const borderWidth = 10; | |
const ballRadius = 10; | |
const drawInterval = 1; | |
const speedMultiplier = 1; | |
// Define the SVG "canvas". This is where we will create our drawing. | |
let svg = d3.select("#tabletop") | |
.attr("width", width) | |
.attr("height", height) | |
.style("background-color", "black"); | |
// Add an inner rectangle. | |
let rect = svg.insert("rect") | |
.attr("x", borderWidth) | |
.attr("y", borderWidth) | |
.attr("width", width - 2 * borderWidth) | |
.attr("height", height - 2 * borderWidth) | |
.attr("fill", "lightgray"); | |
let ball = svg.insert("circle") | |
.attr("cx", width / 2) | |
.attr("cy", height / 2) | |
.attr("r", ballRadius) | |
.attr("fill", "royalblue"); | |
// Randomly build a vector between 0 and 360. From that angle, get the X and Y | |
// movement. | |
let angle = 360.0 * Math.random(); | |
let diffX = Math.sin(angle); | |
let diffY = Math.cos(angle); | |
function moveX() { | |
let posX = Number(d3.select(this).attr("cx")); | |
let nextX = posX + diffX * speedMultiplier; | |
if (nextX < borderWidth + ballRadius || nextX > width - borderWidth - ballRadius) { | |
diffX = -1 * diffX; | |
} | |
return nextX; | |
} | |
function moveY() { | |
let posY = Number(d3.select(this).attr("cy")); | |
let nextY = posY + diffY * speedMultiplier; | |
if (nextY < borderWidth + ballRadius || nextY > height - borderWidth - ballRadius) { | |
diffY = -1 * diffY; | |
} | |
return nextY; | |
} | |
// Move the (x, y) coordinates of the ball every "tick". | |
setInterval(function () { | |
ball.attr("cx", moveX).attr("cy", moveY); | |
}, drawInterval); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment