How to animate properly in a <canvas>? - javascript

So I want to recreate this simple animation effect, which uses a <canavs> :
https://codepen.io/w3devcampus/pen/PpLLKY
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Draw a monster in a canvas</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
</body>
</html>
JavaScript:
function mainLoop() {
ctx.clearRect(0, 0, w, h);
drawMyMonster(xMonster, yMonster);
xMonster += monsterSpeed;
if (((xMonster + 100)> w) || (xMonster < 0)) {
monsterSpeed = -monsterSpeed;
}
}
function drawMyMonster(x, y) {
ctx.save();
ctx.translate(x, y);
ctx.strokeRect(0, 0, 100, 100);
ctx.fillRect(20, 20, 10, 10);
ctx.fillRect(65, 20, 10, 10);
ctx.strokeRect(45, 40, 10, 40);
ctx.strokeRect(35, 84, 30, 10);
ctx.fillRect(38, 84, 10, 10);
ctx.fillRect(52, 84, 10, 10);
ctx.restore();
}
So, I did recreate it, but it wouldn't behave normally. Instead of displaying one frame at a time, it stacks all the frames up each other in the canvas. Here's my version:
https://codepen.io/Undefined_Variable/pen/LraLJQ
HTML:
<html>
<head>
<title>CanvasThingy</title>
</head>
<body>
<canvas id="CanvasForMonster">
No support for you scrub!
</canvas>
</body>
</html>
JavaScript:
var myCanvas, context, w, h;
var xMonster = 60;
var yMonster = 30;
var monsterSpeed = 1;
window.onload = function initial(){
myCanvas = document.body.querySelector('#CanvasForMonster');
w = myCanvas.style.width;
h = myCanvas.style.height;
context = myCanvas.getContext('2d');
ClearCanvas();
}
function ClearCanvas(){
context.clearRect(0, 0, w, h);
DrawFMLface(xMonster, yMonster);
xMonster += monsterSpeed;
if(((xMonster + 175) > 299) || (xMonster < 0) ){
monsterSpeed = -monsterSpeed;
}
requestAnimationFrame(ClearCanvas);
}
function DrawFMLface(x, y){
context.save();
context.translate(x, y);
context.strokeRect(0, 4, 175, 80);
context.strokeStyle = 'black';
context.fillRect(40, 10, 20, 20);
context.strokeStyle = 'black';
context.fillRect(110, 10, 20, 20);
context.strokeStyle = 'black';
context.strokeRect(85, 40, 1, 15);
context.strokeStyle = 'black';
context.strokeRect(42, 70, 90, 0);
context.strokeStyle = 'black';
context.restore();
}
Please tell me how to do this properly without jQuery AT ALL, please. I'm still learning and I don't want any jQuery/Angular/React etc. in my code, please!

Your problem is that the previous faces are not being cleared. The clearing is supposed to be done with this line:
ctx.clearRect(0, 0, w, h);
The problem is that w and h are not set correctly when this is run, so not enough of the canvas is cleared.
This is where you set w and h:
w = myCanvas.style.width;
h = myCanvas.style.height;
This will only work if the width and height were set with CSS, e.g. with an HTML attribute style="width: 200px; height: 200px;", and if you called parseInt to convert the CSS style strings into numbers. But in fact the canvas element’s width and height were set with width and height HTML attributes directly. So you should set w and h with HTMLCanvasElement’s width and height properties:
w = canvas.width;
h = canvas.height;
The original Codepen sets them this way.

Just in case you were looking for a possibly easier way to do this, you can actually avoid JavaScript entirely when creating a simple animation like this by using CSS animations:
#CanvasForMonster {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #000;
}
#Monster {
position: absolute;
top: 25%;
width: 50%;
height: 50%;
animation: bounce 2s alternate linear infinite;
}
#keyframes bounce {
from { left: 0; }
to { left: 50%; }
}
#Monster div {
position: absolute;
}
#Monster .stroke {
border: 1px solid #000;
}
#Monster .fill {
background-color: #000;
}
#Monster .head {
left: 0;
top: 0;
width: 100%;
height: 100%;
}
#Monster .eye {
width: 10%;
height: 10%;
}
#Monster .eye-left {
left: 25%;
top: 25%;
}
#Monster .eye-right {
left: 65%;
top: 25%;
}
#Monster .nose {
left: 50%;
top: 50%;
width: 1px;
height: 10%;
}
#Monster .mouth {
left: 25%;
top: 75%;
width: 50%;
height: 0;
}
<div id="CanvasForMonster">
<div id="Monster">
<div class="stroke head"></div>
<div class="fill eye eye-left"></div>
<div class="fill eye eye-right"></div>
<div class="stroke nose"></div>
<div class="stroke mouth"></div>
</div>
</div>

Everything you have is alright.
The problem is your Globals.
The width of the canvas should be set to:
w = myCanvas.width;
Height set to:
h = myCanvas.height;
You have both set as:
w = myCanvas.style.width;
h = myCanvas.style.height;
Which will not work.
Here is the fork (Demo).
I would highly recommend using JQuery when working with canvas.
When using canvas it should be noted that you want too reference canvas.height, and canvas.width as much as possible rather then using a global that points at the height, and width of the css style.

Related

How do I get my canvas animation to play/stop when the play/pause button is clicked?

How do I get my canvas animation of the rain to start when the play button is clicked and vice versa (stop the rain when the pause button is clicked)?
I really would appreciate a helping hand.
So far I have the rain animation to play as soon as the window is loaded and the audio in the background is the only thing that plays when interacting with the play button.
I'm not sure how to go about getting the rain animation to start so that the audio also plays in sync with the rain and vice versa.
// Get the canvas and context and store in variables
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Set canvas dimensions to window height and width
canvas.width = window.innerHeight;
canvas.height = window.innerHeight;
// Generate the raindrops and apply attributes
var rainNum = 200; // max raindrops
var rainDrops = [];
let isClicked = true;
// Loop through the empty raindrops and apply attributes
for (var i = 0; i < rainNum; i++) {
rainDrops.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
})
}
// Draw raindrops onto canvas
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.lineWidth = 0.1;
context.strokeStyle = "white";
context.beginPath();
for (var i = 0; i < rainNum; i++) {
var r = rainDrops[i];
context.moveTo(r.x, r.y);
context.lineTo(r.x, r.y + 30);
rainDrops[i].y += 13;
context.stroke();
}
if (isClicked == true) {
moveRain();
} else {
return false
}
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
// Animate the raindrops
function moveRain() {
for (var i = 0; i < rainNum; i++) {
// Store current raindrops
var r = rainDrops[i];
// If the rain reaches the bottom, send a new one to the top
if (r.y > canvas.height) {
rainDrops[i] = {
x: Math.random() * canvas.width,
y: 0
};
}
}
}
// Create a reference to the audio
var audioOne = document.querySelector("#audio-1");
function playAudio() {
if (isClicked == true) {
isClicked = false
audioOne.pause();
btn.className = "play";
} else if (isClicked == false) {
isClicked = true
audioOne.play();
btn.className = "pause";
draw()
}
}
html {
height: 100%;
width: 100%;
}
body {
height: 100vh;
width: 100vw;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
height: 100%;
width: 100%;
background-color: transparent;
position: absolute;
z-index: 10;
}
#sky-top {
height: 100%;
width: 100%;
position: absolute;
z-index: 1;
animation: lightning 20s ease-in-out infinite;
}
#keyframes lightning {
/****** This will create a lightning effect every 20 seconds ******/
0% {
background-color: rgb(46, 46, 46);
}
6.25% {
background-color: rgb(46, 46, 46);
}
8% {
background-color: rgb(255, 255, 255);
}
9% {
background-color: rgb(46, 46, 46);
}
11% {
background-color: rgb(255, 255, 255);
}
30% {
background-color: rgb(46, 46, 46);
}
100% {
background-color: rgb(46, 46, 46);
}
}
#sky-bottom {
height: 100%;
width: 100%;
position: absolute;
z-index: 2;
background: linear-gradient(rgba(255, 255, 255, 0), rgb(45, 45, 45));
}
.center-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-align: center;
z-index: 20;
background-color: transparent;
}
.button-center {
position: absolute;
top: 40%;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
.center-container:after,
.button-center {
display: inline-block;
vertical-align: middle;
}
#btn {
height: 130px;
width: 130px;
border: none;
background-size: 100% 100%;
outline: none;
}
.play {
background: url('../image/play-button.png');
border-radius: 50%;
cursor: pointer;
-webkit-filter: drop-shadow(2px 2px 2px #666666);
filter: drop-shadow(2px 2px 2px #666666);
}
.pause {
background: url('../image/pause-button.png');
border-radius: 50%;
cursor: pointer;
-webkit-filter: drop-shadow(2px 2px 2px #666666);
filter: drop-shadow(2px 2px 2px #666666);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rain</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Relax your mind with some rain and thunder.">
<link href="css/styles.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="sky-top"></div>
<div id="sky-bottom"></div>
<canvas id="canvas"></canvas>
<div class="center-container">
<div class="button-center">
<button id="btn" class="play" class="pause" onclick="playAudio()"></button>
</div>
<audio src="audio/rain-and-thunder.mp3" id="audio-1" loop="loop" type="audio/mp3"></audio>
</div>
<script src="js/script.js"></script>
</body>
</html>
First off, the audio file won't work for me here locally (I downloaded my own mp3 - I am working on getting it to work now), so I focused on playing/pausing the canvas animation and ignored the sound functionality. Let's start with the HTML:
<html>
<head>
<link rel = "stylesheet"
type = "text/css"
href = "index.css" />
</head>
<body>
<canvas id="canvas"></canvas>
<div class="center-container">
<div class="button-center">
<button id="btn" class="play" class="pause" onclick="playAudio()"></button>
</div>
<audio loop="loop" id="audio-1" width="100%" height="auto">
<source src="audio/rain-and-thunder.mp3" type="audio/mpeg">
</audio>
</div>
</body>
<script src='index.js'></script>
</html>
You'll see I did a few things to display the canvas properly. For whatever reason, I couldn't see your button and the canvas was showing up blank. I decided to inline CSS the width and height, as well as put the script within the body.
Also, since we are ignoring the sound functionality, I renamed the function to startStopRain() to make more sense in your JS file. Let's talk about that next:
// Get the canvas and context and store in variables
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var audioOne = document.getElementById("audio-1");
// Set canvas dimensions to window height and width
canvas.width = window.innerHeight;
canvas.height = window.innerHeight;
// Generate the raindrops and apply attributes
var rainNum = 200; // max raindrops
var rainDrops = [];
let isClicked = false
// Loop through the empty raindrops and apply attributes
for(var i = 0; i < rainNum; i ++)
{
rainDrops.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
})
}
// Draw raindrops onto canvas
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.lineWidth = 0.1;
context.strokeStyle = "red";
context.beginPath();
for(var i = 0; i < rainNum; i ++)
{
var r = rainDrops[i];
context.moveTo(r.x, r.y);
context.lineTo(r.x, r.y + 30);
rainDrops[i].y += 13;
context.stroke();
}
if (isClicked == true) {
moveRain();
} else{
return false
}
document.getElementById("canvas").onclick = moveRain();
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
// Animate the raindrops
function moveRain(){
for(var i = 0; i < rainNum; i++)
{
// Store current raindrops
var r = rainDrops[i];
// If the rain reaches the bottom, send a new one to the top
if(r.y > canvas.height) {
rainDrops[i] = {x: Math.random() * canvas.width, y: 0};
}
}
}
// Create a reference to the audio
// need to figure out why the audio wont play - this is new to me :D
function playAudio(){
audioOne.play();
if (isClicked == true){
isClicked = false
audioOne.pause();
} else if (isClicked == false){
isClicked = true
audioOne.play();
draw()
}
}
Your original intent was to use two class names on the btn so you could distinguish between play/pause. While there are use cases for using multiple class names, I don't personally believe this is one of them. Instead, I used a global isClicked variable in the script so I could control the flow of the functions.
Follow the isClicked variable from top to bottom to better understand how I used it to call/stop functions. Minus initializing the variable at the top, you'll notice it shows up in only two functions: draw() and startStopRain().
EDIT: The flow control for the sound should be no different. You can use the same isClicked boolean value to determine when the sound should be played or not. If you want, I can update it to reflect that but truthfully, that would be good practice for you. Also, I changed the id of the button to audio-1 since the original code was selecting the element via that specific id

Can't use jQuery to override inline style generated by jQuery?

My code is forking this pen, I also include my code in the stack snippet under this post.
what I want to achieve are:
When the cursor is not inside the body, the eyeball would move randomly ( achieved ).
When the cursor enters the body, the eyeball follows the cursor ( achieved ).
When the cursor leaves the body, the eyeball starts moving randomly again ( not achieved ).
I called the function which is used to move the eyeball randomly in on("mouseleave") event, and it does move to a random position but it will immediately go back to the last cursor position, rather than staying at the new position. Can anyone point me to the right direction to fix the problem?
Thanks!
var
mouseOvering = false,
pupil = $("#pupil"),
eyeball = $("#iris"),
eyeposx = 40,
eyeposy = 20,
r = $(pupil).width()/2,
center = {
x: $(eyeball).width()/2 - r,
y: $(eyeball).height()/2 - r
},
distanceThreshold = $(eyeball).width()/2 - r,
mouseX = 0,
mouseY = 0;
$("body").ready( function(){
if ( !mouseOvering ) {
moveRandomly();
}
});
$("body").on('mouseleave', function(){
mouseOvering = false;
moveRandomly();
console.log("mouseleave");
});
$("body").on('mousemove', function(e){
mouseOvering = true;
console.log("mouseovering");
followCursor(e);
});
function moveRandomly() {
var loop = setInterval(function(){
var xp = Math.floor(Math.random()*80);
var yp = Math.floor(Math.random()*80);
pupil.animate({left:xp, top:yp});
}, 3500);
}
function followCursor(e) {
var d = {
x: e.pageX - r - eyeposx - center.x,
y: e.pageY - r - eyeposy - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX - eyeposx - r;
mouseY = e.pageY - eyeposy - r;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 1 to alter damping/momentum - higher is slower
xp += (mouseX - xp) / 1;
yp += (mouseY - yp) / 1;
pupil.css({left:xp, top:yp});
}, 2);
}
body {
background-color: #D1D3CF;
}
#container {
display: inline;
height: 400px;
width: 400px;
}
#eyeball {
background: radial-gradient(circle at 100px 100px, #EEEEEE, #000);
height: 300px;
width: 300px;
border-radius: 100%;
position: relative;
}
#iris {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #4DC9EF, #000);
height: 80%;
width: 80%;
border-radius: 100%;
position: absolute;
}
#pupil {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #000000, #000);
height: 55%;
width: 55%;
border-radius: 100%;
position: absolute;
}
#keyframes move {
50% {
transform: translate(-50px, 50px);
}
}
#keyframes move2 {
50% {
transform: translate(-20px, 20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="eyeball">
<div id="iris">
<div id="pupil"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
With Javascript you can only track where the cursor is on the webpage. If you shift your cursor outside the body, it's not possible for your code to know where the cursor is.
This is the reason the eye tracking your cursor stops moving when you move your cursor outside the window.
The problem is that once the followcursor function was started it kept on moving back to the last known mouse position, even after the mouse had left the body. I just put a check on your mouseOvering variable inside your followcursor function:
var
mouseOvering = false,
pupil = $("#pupil"),
eyeball = $("#iris"),
eyeposx = 40,
eyeposy = 20,
r = $(pupil).width()/2,
center = {
x: $(eyeball).width()/2 - r,
y: $(eyeball).height()/2 - r
},
distanceThreshold = $(eyeball).width()/2 - r,
mouseX = 0,
mouseY = 0;
$("body").ready( function(){
if ( !mouseOvering ) {
moveRandomly();
}
});
$("body").on('mouseleave', function(){
mouseOvering = false;
console.log("mouseleave");
});
$("body").on('mousemove', function(e){
mouseOvering = true;
console.log("mouseovering");
followCursor(e);
});
function moveRandomly() {
var loop = setInterval(function(){
var xp = Math.floor(Math.random()*80);
var yp = Math.floor(Math.random()*80);
if (!mouseOvering) {
pupil.animate({left:xp, top:yp});
}
}, 3500);
}
function followCursor(e) {
var d = {
x: e.pageX - r - eyeposx - center.x,
y: e.pageY - r - eyeposy - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX - eyeposx - r;
mouseY = e.pageY - eyeposy - r;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 1 to alter damping/momentum - higher is slower
xp += (mouseX - xp) / 1;
yp += (mouseY - yp) / 1;
if (mouseOvering) {
pupil.css({left:xp, top:yp});
}
}, 2);
}
body {
background-color: #D1D3CF;
}
#container {
display: inline;
height: 400px;
width: 400px;
}
#eyeball {
background: radial-gradient(circle at 100px 100px, #EEEEEE, #000);
height: 300px;
width: 300px;
border-radius: 100%;
position: relative;
}
#iris {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #4DC9EF, #000);
height: 80%;
width: 80%;
border-radius: 100%;
position: absolute;
}
#pupil {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #000000, #000);
height: 55%;
width: 55%;
border-radius: 100%;
position: absolute;
}
#keyframes move {
50% {
transform: translate(-50px, 50px);
}
}
#keyframes move2 {
50% {
transform: translate(-20px, 20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="eyeball">
<div id="iris">
<div id="pupil"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>

HTML Canvas and a little issue displaying correctly?

I'm trying to adjust the size to correctly be position more in the middle and a larger div. I would like it to be 500x500. What I'm trying to do is do a classic version of what Windows Paint is.
The issue is adjusting the 'canvas' to the middle stops the paint brush to 'draw'.
Here is the code, I have so far.
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
width: 500px;
height: 500px;
margin: auto;
top: 50%;
left: 50%;
width: 90%;
border: 3px solid #73AD21;
padding: 10px;
}
</style>
</head>
<body>
<div id="paint" >
<canvas id="myCanvas"></canvas>
</div>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var painting = document.getElementById('paint');
var paint_style = getComputedStyle(painting);
canvas.width = parseInt(paint_style.getPropertyValue('width'));
canvas.height = parseInt(paint_style.getPropertyValue('height'));
var mouse = {x: 0, y: 0};
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
ctx.lineWidth = 10;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#00CC99';
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
</script>
</body>
</html>
Get rid of the styling on body and replace it with this:
#paint {
height: 500px;
margin: auto;
width: 90%; /* you also had width: 500px, which one did you want? */
border: 3px solid #73AD21;
padding: 10px;
}
Fiddle - Looks like it's working okay with that change.

Drawing in canvas become offset

I'm trying to draw into a canvas, but the more I go right, the more offset my drawing become.
Anyone have an idea why?
I have included the relevant code below:
CSS
html,body {
width:100%;
height:100%;
background:rgba(0,0,0,.2);
}
#container {
position:relative;
width:700px;
height:450px;
background:#fff;
overflow:hidden;
}
* {
-webkit-user-select: none;
}
canvas {
position: absolute;
top: 0;
left: 0;
background: #ccc;
width: 500px;
height: 200px;
}
HTML
<div id='adContainer'>
<canvas></canvas>
</div>
Javascript
var ctx;
var can = $('canvas');
$(document).ready(function() {
ctx = can[0].getContext('2d');
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.lineWidth = 5;
ctx.lineCap = 'round';
can.on("touchstart", function(event) {
event.preventDefault();
var e = event.originalEvent;
if(e.touches.length == 1) {
var posX = e.touches[0].pageX;
var posY = e.touches[0].pageY;
ctx.moveTo(posX, posY);
}
});
can.on("touchmove", function(event) {
event.preventDefault();
var e = event.originalEvent;
if(e.touches.length == 1) {
var posX = e.touches[0].pageX;
var posY = e.touches[0].pageY;
ctx.lineTo(posX, posY);
ctx.stroke();
}
});
});
Demo: http://jsfiddle.net/8Wtf8/
That is because you define the size of the canvas using CSS.
What happens is that when you don't explicitly define the size of the canvas using its width and height attributes the canvas defaults to size 300 x 150.
In your CSS you are then stretching the canvas element (look at it as an image) to 500px etc. - the content of the canvas is still 300 x 150.
You need to set the width and height on the canvas element itself:
<canvas width=500 height=200 id="myCanvas"></canvas>
and remove the definition from the CSS:
canvas {
position: absolute;
top: 0;
left: 0;
background: #ccc;
/*width: 500px;
height: 200px;*/
}
Also notice that background set by CSS will not be part of the canvas content.

Randomize position of animated object

I have little script that moves objects on orbital and I want to randomize starting position of object.
Here's what I'm talking about:
http://jsfiddle.net/W69s6/1018/
HTML
<div class="orbit">
<div class="circle"></div>
</div>
CSS
.orbit
{
height: 200px;
width: 200px;
background: rgba(0,0,0,0.2);
}
.circle
{
height: 50px;
width: 50px;
background: #00ff00;
position: absolute;
}
JS
$(document).ready(function() {
orbit('.circle', 0, 0.01, 100, 75, 75);
});
function orbit(obj, t, ts, r, x, y)
{
t += ts;
var top = Math.floor(y - (r * Math.sin(t)));
var left = Math.floor(x - (r * Math.cos(t)));
$(obj).animate({
top: top,
left: left,
}, 1, function()
{
orbit(obj, t, ts, r, x, y);
});
}
Is anyone good at math and knows how to change it?
Change the first part of your code:
$(document).ready(function() {
orbit('.circle', Math.random()*100, 0.01, 100, 75, 75);
});

Categories