Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!--
- this example is written by: vchar
- on Sat, 7 July 2018
- -->
- <html>
- <head>
- <title>Animation with Javascript, HMTL and CSS</title>
- <style>
- .container {
- width: 90%;
- height: 90%;
- background-color: azure;
- margin: auto;
- margin-top: 5%;
- }
- .object {
- width: 23px;
- height: 23px;
- border-radius: 9px;
- background-color: coral;
- position: relative;
- left: 0;
- }
- span {
- margin-left: 5%
- }
- </style>
- </head>
- <body>
- <span>Position Tracking: </span><span id="tracker"></span>
- <div class="container" id="container">
- <div class="object" id="object" onclick="start()"></div>
- </div>
- </body>
- <script>
- var h_pos = 0; // horizontal position
- var v_pos = 0; // vertical position
- var h_direction = -1; // horizontal direction
- var v_direction = -1; // vertical direction
- // get the right edge of a container
- var right_edge = document.getElementById("container").offsetWidth;
- // get the bottom edge of a container
- var bottom_edge = document.getElementById("container").offsetHeight;
- // this function control the animation an object by linearly moving it
- // all directions such as up, down, left, right
- function animate() {
- h_direction = get_direction(h_pos, right_edge, h_direction, 23);
- v_direction = get_direction(v_pos, bottom_edge, v_direction, 23)
- h_pos += h_direction * 2;
- v_pos += v_direction * 2;
- move(h_pos, v_pos);
- track(h_pos, v_pos, h_direction, v_direction);
- }
- /*
- * get object direction when it hits its container edge
- * params:
- * - position : the current object position
- * - edge : the objectt container edge, either right or bottom edge,
- * by default left and top edges are set to 0
- * return: object's direction
- */
- function get_direction(position, edge, direction, object_width) {
- if (position >= edge-object_width || position <= 0 ) {
- direction *= -1;
- }
- return direction;
- }
- // move an object base on a given position
- function move(x, y) {
- document.getElementById("object").style.left = x;
- document.getElementById("object").style.top = y;
- }
- // track an object's position
- function track(x, y, x_direction, y_direction) {
- document.getElementById("tracker").innerHTML =
- x_direction + " - " + x + " - " + y_direction + " - " + y;
- }
- // start the animation
- function start() {
- setInterval(animate, 1); // time interval in milisecon(s)
- }
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment