Been trying to run different js scripts on Wordpress in front of the page itself but everytime I try, it ends up creating a specific div with given width and height which stays on top of the page.
I was hoping the script itself would run "over" any div on page as an animated effect (on mouse move)
This is particularly one of the scripts I would like to run through all the pages:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<style>
html, body {
font-family: 'Play', sans-serif;
background: #2b2b2b;
margin: 0;
}
#info {
position: absolute;
left: 10px;
top: 10px;
}
#info {
background: rgba(0,0,0,0.8);
padding: 12px 10px;
margin-bottom: 1px;
color: #fff;
}
#info h1 {
line-height: 22px;
font-weight: 300;
font-size: 18px;
margin: 0;
}
#info h2 {
line-height: 14px;
font-weight: 300;
font-size: 12px;
color: rgba(255,255,255,0.8);
margin: 0 0 6px 0;
}
#info a {
text-transform: uppercase;
text-decoration: none;
border-bottom: 1px dotted rgba(255,255,255,0.2);
margin-right: 4px;
line-height: 20px;
font-size: 10px;
color: rgba(255,255,255,0.5);
}
#info a:hover {
border-bottom: 1px dotted rgba(255,255,255,0.6);
color: rgba(255,255,255,1.0);
}
</style>
</head>
<body>
<div id="container"></div>
<script src='https://rawgithub.com/soulwire/sketch.js/v1.0/js/sketch.min.js'></script>
<script>
function Particle( x, y, radius ) {
this.init( x, y, radius );
}
Particle.prototype = {
init: function( x, y, radius ) {
this.alive = true;
this.radius = radius || 10;
this.wander = 0.15;
this.theta = random( TWO_PI );
this.drag = 0.92;
this.color = '#fff';
this.x = x || 0.0;
this.y = y || 0.0;
this.vx = 0.0;
this.vy = 0.0;
},
move: function() {
this.x += this.vx;
this.y += this.vy;
this.vx *= this.drag;
this.vy *= this.drag;
this.theta += random( -0.5, 0.5 ) * this.wander;
this.vx += sin( this.theta ) * 0.1;
this.vy += cos( this.theta ) * 0.1;
this.radius *= 0.96;
this.alive = this.radius > 0.5;
},
draw: function( ctx ) {
ctx.beginPath();
ctx.arc( this.x, this.y, this.radius, 0, TWO_PI );
ctx.fillStyle = this.color;
ctx.fill();
}
};
// ----------------------------------------
// Example
// ----------------------------------------
var MAX_PARTICLES = 280;
var COLOURS = [ '#69D2E7', '#A7DBD8', '#E0E4CC', '#F38630', '#FA6900', '#FF4E50', '#F9D423' ];
var particles = [];
var pool = [];
var demo = Sketch.create({
container: document.getElementById( 'container' )
});
demo.setup = function() {
// Set off some initial particles.
var i, x, y;
for ( i = 0; i < 20; i++ ) {
x = ( demo.width * 0.5 ) + random( -100, 100 );
y = ( demo.height * 0.5 ) + random( -100, 100 );
demo.spawn( x, y );
}
};
demo.spawn = function( x, y ) {
if ( particles.length >= MAX_PARTICLES )
pool.push( particles.shift() );
particle = pool.length ? pool.pop() : new Particle();
particle.init( x, y, random( 5, 40 ) );
particle.wander = random( 0.5, 2.0 );
particle.color = random( COLOURS );
particle.drag = random( 0.9, 0.99 );
theta = random( TWO_PI );
force = random( 2, 8 );
particle.vx = sin( theta ) * force;
particle.vy = cos( theta ) * force;
particles.push( particle );
}
demo.update = function() {
var i, particle;
for ( i = particles.length - 1; i >= 0; i-- ) {
particle = particles[i];
if ( particle.alive ) particle.move();
else pool.push( particles.splice( i, 1 )[0] );
}
};
demo.draw = function() {
demo.globalCompositeOperation = 'lighter';
for ( var i = particles.length - 1; i >= 0; i-- ) {
particles[i].draw( demo );
}
};
demo.mousemove = function() {
var particle, theta, force, touch, max, i, j, n;
for ( i = 0, n = demo.touches.length; i < n; i++ ) {
touch = demo.touches[i], max = random( 1, 4 );
for ( j = 0; j < max; j++ ) demo.spawn( touch.x, touch.y );
}
};
</script>
</body>
</html>
I would like the particles to run through the site.
Any help with it?
First I would start by making sure you properly enqueue the your javascript and css:
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
wp_enqueue_scripts is the proper hook to use when enqueuing items that
are meant to appear on the front end.
Related
i have a html script with button and onclick function script that should take me to google.com, but it doesn't seem to work. Been stuck with this for hours. Im also new to HTML.
Tried everything. Line 336 and 353 should be the needed content. And line 136 should be the button itself. I don't understand whats wrong. Anyone ever have had this issue?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon/text/javascript" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>SpyBanter - SpyBanter's Official WebSite</title>
<style type="text/css">
body {
overflow: hidden;
margin: 0;
}
body:before {
content: '';
background: #c4252a url(http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/cheap_diagonal_fabric.png);
background-blend-mode: multiply;
mix-blend-mode: multiply;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 10;
}
canvas {
opacity: 0;
transition: 1s opacity cubic-bezier(0.55, 0, 0.1, 1);
}
canvas.ready {
opacity: 0.4;
}
.intro {
position: absolute;
padding: 20px;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
text-align: center;
color: #fafafa;
z-index: 10;
width: 100%;
max-width: 700px;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
text-shadow: 0px 5px 20px black;
}
.intro h1 {
font-size: 40px;
font-weight: 300;
letter-spacing: 2px;
}
.intro p {
letter-spacing: 1px;
line-height: 24px;
}
#btnclose {
background-color: indianred;
border-color: darkred;
}
}
#btnnup:hover, #btnsisu:hover, #btncmd:hover {
background-color: #3e8e41;
}
#btnnup:active, #btnsisu:active, #btncmd:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#btnsisu {
left: 108px;
top: 105px;
}
#btncmd {
left: -311px;
top: -88px;
}
#content {
width: 100%;
height: auto;
min-height: 580px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<canvas id="canvas" data-image="http://unsplash.it/g/450/200/?random=1"></canvas>
<div class="intro">
<h1>Interactive mosaic background</h1>
<p>Had to do this effect in a recent project and wanted to share it with you :). To change the background, edit the data-image on the canvas tag. You can also change the magnet effect intensity by changing the magnet variable</p>
<button id="btncmd">Videos</button>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script type="application/javascript">
(function () {
// Variables
var Photo, addListeners, canvas, createGrid, ctx, gridItem, grids, height, img, imgInfo, imgSrc, imgs, init, magnet, mouse, populateCanvas, render, resizeCanvas, rotateAndPaintImage, updateMouse, useGrid, width;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
imgSrc = canvas.dataset.image;
img = new Image();
useGrid = true;
imgInfo = {};
imgs = [];
grids = [];
magnet = 2000;
mouse = {
x: 1,
y: 0 };
init = function () {
addListeners();
img.onload = function (e) {
var numberToShow;
// Check for firefox.
imgInfo.width = e.path ? e.path[0].width : e.target.width;
imgInfo.height = e.path ? e.path[0].height : e.target.height;
numberToShow = Math.ceil(window.innerWidth / imgInfo.width) * Math.ceil(window.innerHeight / imgInfo.height);
if (useGrid) {
createGrid();
}
populateCanvas(numberToShow * 4);
canvas.classList.add('ready');
return render();
};
return img.src = imgSrc;
};
addListeners = function () {
window.addEventListener('resize', resizeCanvas);
window.addEventListener('mousemove', updateMouse);
return window.addEventListener('touchmove', updateMouse);
};
updateMouse = function (e) {
mouse.x = e.clientX;
return mouse.y = e.clientY;
};
resizeCanvas = function () {
width = canvas.width = window.innerWidth;
return height = canvas.height = window.innerHeight;
};
populateCanvas = function (nb) {
var i, p, results;
i = 0;
results = [];
while (i <= nb) {
p = new Photo();
imgs.push(p);
results.push(i++);
}
return results;
};
createGrid = function () {
var c, grid, i, imgScale, item, j, k, l, r, ref, ref1, ref2, results, x, y;
imgScale = 0.5;
grid = {
row: Math.ceil(window.innerWidth / (imgInfo.width * imgScale)),
cols: Math.ceil(window.innerHeight / (imgInfo.height * imgScale)),
rowWidth: imgInfo.width * imgScale,
colHeight: imgInfo.height * imgScale };
for (r = j = 0, ref = grid.row; 0 <= ref ? j < ref : j > ref; r = 0 <= ref ? ++j : --j) {
x = r * grid.rowWidth;
for (c = k = 0, ref1 = grid.cols; 0 <= ref1 ? k < ref1 : k > ref1; c = 0 <= ref1 ? ++k : --k) {
y = c * grid.colHeight;
item = new gridItem(x, y, grid.rowWidth, grid.colHeight);
grids.push(item);
}
}
results = [];
for (i = l = 0, ref2 = grids.length; 0 <= ref2 ? l < ref2 : l > ref2; i = 0 <= ref2 ? ++l : --l) {
results.push(grids[i].draw());
}
return results;
};
gridItem = function (x = 0, y = 0, w, h) {
this.draw = function () {
ctx.drawImage(img, x, y, w, h);
};
};
Photo = function () {
var TO_RADIANS, finalX, finalY, forceX, forceY, h, r, seed, w, x, y;
seed = Math.random() * (2.5 - 0.7) + 0.7;
w = imgInfo.width / seed;
h = imgInfo.height / seed;
x = window.innerWidth * Math.random();
finalX = x;
y = window.innerHeight * Math.random();
finalY = y;
console.log(`INIT Y :: ${finalY} || INIT X :: ${finalX}`);
r = Math.random() * (180 - -180) + -180;
forceX = 0;
forceY = 0;
TO_RADIANS = Math.PI / 180;
this.update = function () {
var distance, dx, dy, powerX, powerY, x0, x1, y0, y1;
x0 = x;
y0 = y;
x1 = mouse.x;
y1 = mouse.y;
dx = x1 - x0;
dy = y1 - y0;
distance = Math.sqrt(dx * dx + dy * dy);
powerX = x0 - dx / distance * magnet / distance;
powerY = y0 - dy / distance * magnet / distance;
forceX = (forceX + (finalX - x0) / 2) / 2.1;
forceY = (forceY + (finalY - y0) / 2) / 2.2;
x = powerX + forceX;
y = powerY + forceY;
};
this.draw = function () {
return rotateAndPaintImage(ctx, img, r * TO_RADIANS, x, y, w / 2, h / 2, w, h);
};
};
rotateAndPaintImage = function (context, image, angle, positionX, positionY, axisX, axisY, widthX, widthY) {
context.translate(positionX, positionY);
context.rotate(angle);
context.drawImage(image, -axisX, -axisY, widthX, widthY);
context.rotate(-angle);
return context.translate(-positionX, -positionY);
};
render = function () {
var x, y;
x = 0;
y = 0;
ctx.clearRect(0, 0, width, height);
while (y < grids.length) {
grids[y].draw();
y++;
}
while (x < imgs.length) {
imgs[x].update();
imgs[x].draw();
x++;
}
return requestAnimationFrame(render);
};
init();
}).call(this);
cmd = function () {
window.location.href = "https://www.google.com/";
}
function cmd() {
window.location.href = "https://www.google.com/";
}
btnclose.onclick = cmd;
btnnup.onclick = cmd;
btncmd.onclick = cmd;
//# sourceURL=coffeescript
//# sourceURL=pen.js
</script>
<script type="application/javascript">
window.onload = function() {
main.style.opacity = "1";
}
function show(){
main.style.opacity = "1";
}
function close() {
main.style.opacity = "0";
$.post('http://tt_help/close', JSON.stringify({
}));
}
function cmd() {
window.location.href = "https://www.google.com/";
}
function sisukord() {
let id = $(this).attr('content');
console.log(id)
let docs = `https://docs.google.com/document/d/e/2PACX-1vSXxzowHucTNRBwduXT-pDoGQT4blGJhOvgnzIYmpEe2DwU4mimf84RZ8orvUGpm2vPsPDdkkVAnFkq/pub?embedded=true${id}`;
$('#main iframe').attr('src', docs);
}
window.addEventListener('message', function(event) {
if (event.data.type == "open") {
main.style.opacity = "1";
}
});
btnclose.onclick = cmd;
btncmd.onclick = cmd;
btnsisu.onclick = cmd;
</script>
</body>
If you're trying to make a button that takes you to google.com, I would advise you to use an a tag, not a button tag. The tag automatically links you to your desired destination when clicked.
Example:
Example
If you want the link to look like a button, then simply look at the css options. I would advise you to look here: https://www.w3schools.com/css/css_link.asp
a {
background-image:linear-gradient(to bottom, lightblue, aquamarine);
padding:5px;
text-decoration:none;
color:black;
padding-right:50px;
padding-left:50px;
margin-top: 50px;
margin-left: 50px;
display: inline-block;
font-size:25px;
border-radius:5px;
box-shadow: 1px 1px green;
}
Example
If you are determined to use a <button> tag, then all you need to do is within that button tag add an onclick attribute. So, you would change your code to <button id="btncmd" onclick="cmd()">Videos</button>.
Example of what you want:
function cmd() {
window.location.href = "https://www.example.com/"; // I'm using example but you can use google.
}
<button id="btncmd" onclick="cmd()">Videos</button>
You did not define btncmd. Adding this line to your code solves the problem:
var btncmd = document.getElementById("btncmd");
I have nice Beautiful Stars Canvas Background script, and i wonder- how do i Display a DIV ontop of that Canvas script.
I try to put the DIV in or under the canvas tags (you can see the results on the link below) but it display nothing, or bring it at the bottom of the page in a way that you have no way to see it .
Here is my code:
HTML:
<canvas></canvas>
<div style="background-color:red">this is a test</div>
CSS:
body{
margin: 0;
overflow: hidden;
background: black
}
JS:
var n_stars = 150
var colors = [ '#176ab6', '#fb9b39']
for ( let i = 0; i < 98; i++) {
colors.push( '#fff')
}
var canvas = document.querySelector('canvas')
canvas.width = innerWidth
canvas.height = innerHeight
addEventListener( 'resize', () => {
canvas.width = innerWidth
canvas.height = innerHeight
stars = []
init()
})
canvas.style.background = '#000'
var c = canvas.getContext('2d')
const randomInt = ( max, min) => Math.floor( Math.random() * (max - min) + min)
var bg = c.createRadialGradient( canvas.width/ 2, canvas.height * 3, canvas.height ,canvas.width/ 2,canvas.height , canvas.height * 4);
bg.addColorStop(0,"#32465E");
bg.addColorStop(.4,"#000814");
bg.addColorStop(.8,"#000814");
bg.addColorStop(1,"#000");
class Star {
constructor( x, y, radius, color) {
this.x = x || randomInt( 0, canvas.width)
this.y = y || randomInt( 0, canvas.height)
this.radius = radius || Math.random() * 1.1
this.color = color || colors[randomInt(0, colors.length)]
this.dy = -Math.random() * .3
}
draw () {
c.beginPath()
c.arc( this.x, this.y, this.radius, 0, Math.PI *2 )
c.shadowBlur = randomInt( 3, 15)
c.shadowColor = this.color
c.strokeStyle = this.color
c.fillStyle = 'rgba( 255, 255, 255, .5)'
c.fill()
c.stroke()
c.closePath()
}
update( arrayStars = [] ) {
if ( this.y - this.radius < 0 ) this.createNewStar( arrayStars )
this.y += this.dy
this.draw()
}
createNewStar( arrayStars = [] ) {
let i = arrayStars.indexOf( this )
arrayStars.splice( i, 1)
arrayStars.push( new Star( false, canvas.height + 5))
}
}
var stars = []
function init() {
for( let i = 0; i < n_stars; i++ ) {
stars.push( new Star( ) )
}
}
init()
function animate() {
requestAnimationFrame( animate)
c.clearRect( 0, 0, canvas.width, canvas.height)
c.fillStyle = bg
c.fillRect(0, 0, canvas.width, canvas.height)
stars.forEach( s => s.update( stars ))
}
animate()
Here is a live one: Codepen
You mean something like this (used a wrapper element and positioned div absolutely on top of canvas element):
var n_stars = 150
var colors = [ '#176ab6', '#fb9b39']
for ( let i = 0; i < 98; i++) {
colors.push( '#fff')
}
var canvas = document.querySelector('canvas')
canvas.width = innerWidth
canvas.height = innerHeight
addEventListener( 'resize', () => {
canvas.width = innerWidth
canvas.height = innerHeight
stars = []
init()
})
canvas.style.background = '#000'
var c = canvas.getContext('2d')
const randomInt = ( max, min) => Math.floor( Math.random() * (max - min) + min)
var bg = c.createRadialGradient( canvas.width/ 2, canvas.height * 3, canvas.height ,canvas.width/ 2,canvas.height , canvas.height * 4);
bg.addColorStop(0,"#32465E");
bg.addColorStop(.4,"#000814");
bg.addColorStop(.8,"#000814");
bg.addColorStop(1,"#000");
class Star {
constructor( x, y, radius, color) {
this.x = x || randomInt( 0, canvas.width)
this.y = y || randomInt( 0, canvas.height)
this.radius = radius || Math.random() * 1.1
this.color = color || colors[randomInt(0, colors.length)]
this.dy = -Math.random() * .3
}
draw () {
c.beginPath()
c.arc( this.x, this.y, this.radius, 0, Math.PI *2 )
c.shadowBlur = randomInt( 3, 15)
c.shadowColor = this.color
c.strokeStyle = this.color
c.fillStyle = 'rgba( 255, 255, 255, .5)'
c.fill()
c.stroke()
c.closePath()
}
update( arrayStars = [] ) {
if ( this.y - this.radius < 0 ) this.createNewStar( arrayStars )
this.y += this.dy
this.draw()
}
createNewStar( arrayStars = [] ) {
let i = arrayStars.indexOf( this )
arrayStars.splice( i, 1)
arrayStars.push( new Star( false, canvas.height + 5))
}
}
var stars = []
function init() {
for( let i = 0; i < n_stars; i++ ) {
stars.push( new Star( ) )
}
}
init()
function animate() {
requestAnimationFrame( animate)
c.clearRect( 0, 0, canvas.width, canvas.height)
c.fillStyle = bg
c.fillRect(0, 0, canvas.width, canvas.height)
stars.forEach( s => s.update( stars ))
}
animate()
body{
margin: 0;
overflow: hidden;
background: black
}
.wrapper{
position: relative;
display: block;
}
.wrapper > canvas {
position: relative;
display: block;
}
.wrapper > div {
position: absolute;
z-index: 10;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
display: block;
}
<div class="wrapper">
<canvas></canvas>
<div style="background-color:red">this is a test</div>
</div>
I use sketch.js plugin in my website but If I use it will be not responsive and the horizontal scroll will be appear I don't need to depend on body { overflow: hidden }so what is the solution:
Here my code:
// ----------------------------------------
// Particle
// ----------------------------------------
function Particle(x, y, radius) {
this.init(x, y, radius);
}
Particle.prototype = {
init: function (x, y, radius) {
this.alive = true;
this.radius = radius || 10;
this.wander = 0.15;
this.theta = random(TWO_PI);
this.drag = 0.92;
this.color = '#fff';
this.x = x || 0.0;
this.y = y || 0.0;
this.vx = 0.0;
this.vy = 0.0;
},
move: function () {
this.x += this.vx;
this.y += this.vy;
this.vx *= this.drag;
this.vy *= this.drag;
this.theta += random(-0.5, 0.5) * this.wander;
this.vx += sin(this.theta) * 0.1;
this.vy += cos(this.theta) * 0.1;
this.radius *= 0.96;
this.alive = this.radius > 0.5;
},
draw: function (ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, TWO_PI);
ctx.fillStyle = this.color;
ctx.fill();
}
};
// ----------------------------------------
// Example
// ----------------------------------------
var MAX_PARTICLES = 280;
var COLOURS = ['#69D2E7', '#A7DBD8', '#E0E4CC', '#F38630', '#FA6900', '#FF4E50', '#F9D423'];
var particles = [];
var pool = [];
var demo = Sketch.create({
container: document.getElementById('particles'),
retina: 'auto'
});
demo.setup = function () {
// Set off some initial particles.
var i, x, y;
for (i = 0; i < 20; i++) {
x = (demo.width * 0.5) + random(-100, 100);
y = (demo.height * 0.5) + random(-100, 100);
demo.spawn(x, y);
}
};
demo.spawn = function (x, y) {
var particle, theta, force;
if (particles.length >= MAX_PARTICLES)
pool.push(particles.shift());
particle = pool.length ? pool.pop() : new Particle();
particle.init(x, y, random(5, 40));
particle.wander = random(0.5, 2.0);
particle.color = random(COLOURS);
particle.drag = random(0.9, 0.99);
theta = random(TWO_PI);
force = random(2, 8);
particle.vx = sin(theta) * force;
particle.vy = cos(theta) * force;
particles.push(particle);
};
demo.update = function () {
var i, particle;
for (i = particles.length - 1; i >= 0; i--) {
particle = particles[i];
if (particle.alive) particle.move();
else pool.push(particles.splice(i, 1)[0]);
}
};
demo.draw = function () {
demo.globalCompositeOperation = 'lighter';
for (var i = particles.length - 1; i >= 0; i--) {
particles[i].draw(demo);
}
};
demo.mousemove = function () {
var particle, theta, force, touch, max, i, j, n;
for (i = 0, n = demo.touches.length; i < n; i++) {
touch = demo.touches[i], max = random(1, 4);
for (j = 0; j < max; j++) {
demo.spawn(touch.x, touch.y);
}
}
};
html, body{
height:100%;
}
ul{
margin:0;
padding:0;
}
section {
padding: 50px 0;
}
#home {
width: 100%;
height:100%;
position: relative;
padding: 50px;
background-image: url(../images/cover1.jpg);
background-position:center center;
background-size: cover;
}
#home #particles {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left:0;
background-color:#333333;
}
#home .overlay {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.60);
}
#home .text-content {
width: 65%;
margin: auto;
padding: 10px;
position: absolute;
top: 50%;
right: 0;
left: 0;
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
color:#ffffff;
text-align: center;
}
<script src="http://soulwire.github.io/sketch.js/js/sketch.js"></script>
<section id="home" >
<div class="overlay">
<div id="particles">
</div>
<div class="text-content">
content
</div>
</div>
</section>
Please run code snippet in full screen
try this, I fixed it with negative margin on canvas
#particles canvas{
margin:-15px -15px 0 0;
}
https://jsfiddle.net/mkdizajn/pLohsbnu/
I am trying to include this Codepen into a basic website for school.
The issue is that the code with a few tweaks, will not load locally. I have even put my entire website into Codepen as a test and it worked.
It should just be the cloth simulation and nothing else.
Here is the HTML and CSS in its smallest form.
<!doctype html>
<html>
<head>
<style>
body {
background: #2F4F4F;
}
#c {
display: block;
margin: 20px auto 0;
}
</style>
<meta charset="utf-8">
<title>Test</title>
<script type="text/javascript" src="Website/JavaScript/ClothSimulation.js"></script>
</head>
<body>
<canvas id="c"></canvas>
<div id="top">
<a id="close"></a>
</div>
</body>
</html>
The JS is very big as it is a cloth simulation.
document.getElementById('close').onmousedown = function(e) {
e.preventDefault();
document.getElementById('info').style.display = 'none';
return false;
};
// settings
var physics_accuracy = 3,
mouse_influence = 20,
mouse_cut = 5,
gravity = 1200,
cloth_height = 30,
cloth_width = 50,
start_y = 20,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
var Point = function(x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
};
Point.prototype.update = function(delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0
};
Point.prototype.draw = function() {
if (!this.constraints.length) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function() {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function(point) {
this.constraints.push(
new Constraint(this, point)
);
};
Point.prototype.remove_constraint = function(constraint) {
this.constraints.splice(this.constraints.indexOf(constraint), 1);
};
Point.prototype.add_force = function(x, y) {
this.vx += x;
this.vy += y;
};
Point.prototype.pin = function(pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function(p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function() {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.5;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
Constraint.prototype.draw = function() {
ctx.moveTo(this.p1.x, this.p1.y);
ctx.lineTo(this.p2.x, this.p2.y);
};
var Cloth = function() {
this.points = [];
var start_x = canvas.width / 2 - cloth_width * spacing / 2;
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])
this.points.push(p);
}
}
};
Cloth.prototype.update = function() {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(.016);
};
Cloth.prototype.draw = function() {
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
function start() {
canvas.onmousedown = function(e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
mouse.down = true;
e.preventDefault();
};
canvas.onmouseup = function(e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function(e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
e.preventDefault();
};
canvas.oncontextmenu = function(e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = '#888';
cloth = new Cloth();
update();
}
window.onload = function() {
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
canvas.width = 560;
canvas.height = 350;
start();
};
Thank you for your help.
Assuming you have copy and pasted the website exactly how it is, you're missing opening and closing style tags around the CSS, and script tags around the JS.
Your code works, but you need this tags:
<script type="text/javascript"> YOUR JAVASCRIPT HERE </script>
<style type="text/css"> YOUR CSS HERE </style>
/*
Copyright (c) 2013 dissimulate at Codepen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
document.getElementById('close').onmousedown = function(e) {
e.preventDefault();
document.getElementById('info').style.display = 'none';
return false;
};
// settings
var physics_accuracy = 3,
mouse_influence = 20,
mouse_cut = 5,
gravity = 1200,
cloth_height = 30,
cloth_width = 50,
start_y = 20,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
var Point = function(x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
};
Point.prototype.update = function(delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0
};
Point.prototype.draw = function() {
if (!this.constraints.length) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function() {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function(point) {
this.constraints.push(
new Constraint(this, point)
);
};
Point.prototype.remove_constraint = function(constraint) {
this.constraints.splice(this.constraints.indexOf(constraint), 1);
};
Point.prototype.add_force = function(x, y) {
this.vx += x;
this.vy += y;
};
Point.prototype.pin = function(pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function(p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function() {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.5;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
Constraint.prototype.draw = function() {
ctx.moveTo(this.p1.x, this.p1.y);
ctx.lineTo(this.p2.x, this.p2.y);
};
var Cloth = function() {
this.points = [];
var start_x = canvas.width / 2 - cloth_width * spacing / 2;
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])
this.points.push(p);
}
}
};
Cloth.prototype.update = function() {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(.016);
};
Cloth.prototype.draw = function() {
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
function start() {
canvas.onmousedown = function(e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
mouse.down = true;
e.preventDefault();
};
canvas.onmouseup = function(e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function(e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
e.preventDefault();
};
canvas.oncontextmenu = function(e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = '#888';
cloth = new Cloth();
update();
}
window.onload = function() {
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
canvas.width = 560;
canvas.height = 350;
start();
};
#charset "utf-8";
body {
line-height: 1.4;
font-size: 100%;
font-family: allerta;
margin-right: auto;
margin-left: auto;
margin-bottom: 0;
padding: 0;
color: #646464;
font-style: normal;
font-weight: 400;
background-color: #2F4F4F;
}
.center {
margin-bottom: 40px;
display: flex;
justify-content: center;
height: 50px;
padding-top: 132px;
}
.button-wrap {
margin-right: 25px;
top: 133px;
margin-top: -139px;
}
.rad-button {
white-space: nowrap;
border-radius: 4px;
position: relative;
border: none;
background: none;
font-family: allerta;
width: 200px;
height: 200px;
cursor: pointer;
transition: 0.1s all ease;
font-size: 32px;
font-weight: 400;
color: #777;
border-bottom: 1px solid #ccc;
box-shadow: 0px 0px 0px 0px #B8B8B8;
font-style: normal;
}
.rad-button.good {
background-color: #FAEBD7;
color: #2F4F4F;
border-bottom: 1px solid #759f87;
}
.rad-button.good:hover {
background-color: #caf3db;
top: -2px;
border-bottom: 4px solid #759f87;
box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.25);
}
.rad-button.good:active {
top: 0px;
border: 1px solid #759f87;
background-color: #a5dabc;
box-shadow: inset 0px 0px 4px rgba(0, 0, 0, 0.25);
}
.fade {
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: fadein 2s; /* Firefox < 16 */
-ms-animation: fadein 2s; /* Internet Explorer */
-o-animation: fadein 2s; /* Opera < 12.1 */
animation: fadein 2s;
}
#keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Firefox < 16 */
#-moz-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Safari, Chrome and Opera > 12.1 */
#-webkit-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Internet Explorer */
#-ms-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Opera < 12.1 */
#-o-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
ul, ol, dl {
padding: 0;
margin: 0;
}
h1 {
font-size: 200%;
color: #FAEBD7;
font-weight: 400;
font-family: allerta;
font-style: normal;
text-align: center;
margin-left: -26px;
}
h2{
display: table-cell;
text-align: center;
vertical-align: middle;
color: #2F4F4F;
text-shadow: 0px 0px;
font-size: x-large;
}
h3, h4, h5, h6, p {
margin-top: 0;
padding-right: 15px;
padding-left: 15px;
color: #FAEBD7;
font-family: allerta;
font-style: normal;
font-weight: 400;
}
a img {
border: none;
}
a:link {
color: #FAEBD7;
text-decoration: none;
font-family: allerta;
font-style: normal;
font-weight: 400;
}
a:visited {
color: #6E6C64;
text-decoration: underline;
}
a:hover, a:active, a:focus {
text-decoration: none;
color: #CAF3DB;
font-family: allerta;
font-style: normal;
font-weight: 400;
text-align: center;
}
.container {
width: 960px;
background-color: #2F4F4F;
margin: 0 auto;
}
header {
background-color: #2F4F4F;
}
.sidebar1 {
float: right;
width: 180px;
background-color: #2F4F4F;
padding-bottom: 10px;
}
.content {
padding: 10px 0;
width: 780px;
display: inline;
top: 10px;
}
.content ul, .content ol {
padding: 0 15px 15px 40px;
}
nav ul{
list-style: none;
border-top: 1px solid #666;
margin-bottom: 15px;
}
nav li {
border-bottom: 1px solid #666;
}
nav a, nav a:visited {
padding: 5px 5px 5px 15px;
display: block;
width: 160px;
text-decoration: none;
background-color: #2F4F4F;
}
nav a:hover, nav a:active, nav a:focus {
background-color: #2F4F4F;
color: #FFF;
min-width: 0px;
top: 0px;
}
/* ~~ The footer ~~ */
footer {
padding: 10px 0;
background-color: #2F4F4F;
position: relative;
clear: both;
}
header, section, footer, aside, article, figure {
display: block;
color: #FAEBD7;
text-align: center;
left: -14px;
top: 134px;
}
#c {
display: block;
margin: 20px auto 0;
}
<html>
<head>
<meta charset="utf-8">
<title>Ewan Lyon Home</title>
<link href="../CSS/HTML5_twoColFixRtHdr.css" rel="stylesheet" type="text/css"><!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
<script>var __adobewebfontsappname__="dreamweaver"</script>
<script src="http://use.edgefonts.net/allerta:n4:default.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<article class="content">
<h1>Ewan Lyon</h1>
<div class = "center">
<div class = "button-wrap">
<button class = "rad-button good flat">Photoshop</button>
</div>
<div class = "button-wrap">
<a href="Illustrator.html">
<button class = "rad-button good flat">Illustrator</button>
</a>
</div>
</div>
<div class = "center">
<div class = "button-wrap">
<button class = "rad-button good flat">About Me</button>
</div>
<div class = "button-wrap">
<button class = "rad-button good flat">RICE</button>
</div>
</div>
<script type="text/javascript" src="../JavaScript/ClothSimulation.js"></script>
<canvas id="c"></canvas>
<div id="top">
<a id="close"></a>
</div>
<footer>
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png" /></a><br />Ewan Lyon
</footer>
</article>
</div>
</body>
</html>
I am trying to change the number of bouncing balls in a simulation. I am passing the required number using Socket.IO, but I'm struggling to change the number of balls. Here is the JavaScript:
var width = 100,
height = 200,
numBalls,
balls;
$(document).ready(function() {
var socket = io();
socket.on('message', function (data) {
console.log(data.count);
numBalls = data.count
});
$('#myCanvas').click(bounce);
// create an array of balls
balls = new Array(numBalls);
for(i = 0 ; i < numBalls ; i++){
balls[i] = new Ball();
}
});
function Ball(){
// random radius
this.radius = Math.floor(Math.random()*(10-5+1))+5;
// random x and y
this.x = Math.floor(Math.random()*(width-this.radius+1))+this.radius;
this.y = Math.floor(Math.random()*(width-this.radius+1))+this.radius;
// random direction, +1 or -1
this.dx = Math.floor(Math.random()*2) * 2 - 1;
this.dy = Math.floor(Math.random()*2) * 2 - 1;
//random colour, r, g or b
var rcol = Math.floor(Math.random()*3);
this.col = rcol==0 ? "red" :
rcol==1 ? "blue" : "green";
}
// draw the balls on the canvas
function draw(){
var canvas = document.getElementById("myCanvas");
// check if supported
if(canvas.getContext){
var ctx=canvas.getContext("2d");
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = 0.5;
ctx.strokeStyle="black";
// draw each ball
for(i = 0; i < numBalls ; i++){
var ball = balls[i];
ctx.fillStyle=ball.col;
ctx.beginPath();
// check bounds
// change direction if hitting border
if(ball.x<=ball.radius ||
ball.x >= (width-ball.radius)){
ball.dx *= -1;
}
if(ball.y<=ball.radius ||
ball.y >= (height-ball.radius)){
ball.dy *= -1;
}
// move ball
ball.x += ball.dx;
ball.y += ball.dy;
// draw it
ctx.arc(ball.x, ball.y, ball.radius, 0, 2*Math.PI, false);
ctx.stroke();
ctx.fill();
}
}
else{
//canvas not supported
}
}
// calls draw every 10 millis
function bounce(){
setInterval(draw, 10);
}
Let's say newNumBalls is the new number of balls.
If newNumBalls is less than numBalls, you want to remove elements from balls. You can do that by taking a slice of balls and assigning it to balls.
If newNumBalls is greater than numBalls, you want to make new balls and add them to balls. You can do that with push.
The complete logic is this:
if (newNumBalls < numBalls) {
balls = balls.slice(0, newNumBalls);
} else {
for (var i = numBalls; i < newNumBalls; ++i) {
balls.push(new Ball());
}
}
numBalls = newNumBalls;
Below is a snippet that implements this logic.
var width,
height,
numBalls = 10,
balls;
$('#setNumBalls').click(function () {
var newNumBalls = parseInt($('#inputNumBalls').val(), 10);
if (newNumBalls < numBalls) {
balls = balls.slice(0, newNumBalls);
//$('#display').html('Removed ' + (numBalls - newNumBalls) + ' balls');
} else {
for (var i = numBalls; i < newNumBalls; ++i) {
balls.push(new Ball());
}
//$('#display').html('Added ' + (newNumBalls - numBalls) + ' new balls');
}
numBalls = newNumBalls;
});
$(document).ready(function() {
width = $('#myCanvas').width();
height = $('#myCanvas').height();
var canvas = $('#myCanvas')[0];
canvas.width = width;
canvas.height = height;
$('#inputNumBalls').val(numBalls);
// create an array of balls
balls = new Array(numBalls);
for(i = 0 ; i < numBalls ; i++){
balls[i] = new Ball();
}
bounce();
});
function Ball(){
// random radius
this.radius = Math.floor(Math.random()*(10-5+1))+5;
// random x and y
var margin = 2 * this.radius;
this.x = Math.floor(Math.random()*(width-margin))+margin/2;
this.y = Math.floor(Math.random()*(width-margin+1))+margin/2;
// random direction, +1 or -1
this.dx = Math.floor(Math.random()*2) * 2 - 1;
this.dy = Math.floor(Math.random()*2) * 2 - 1;
//random colour, r, g or b
var rcol = Math.floor(Math.random()*3);
this.col = rcol==0 ? "red" :
rcol==1 ? "blue" : "green";
}
// draw the balls on the canvas
function draw(){
var canvas = $('#myCanvas')[0];
// check if supported
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
//clear canvas
ctx.clearRect(0, 0, width, height);
ctx.globalAlpha = 0.5;
ctx.strokeStyle="black";
// draw each ball
for(var i = 0; i < numBalls ; i++){
var ball = balls[i];
ctx.fillStyle = ball.col;
ctx.beginPath();
// check bounds
// change direction if hitting border
if(ball.x <= ball.radius ||
ball.x >= (width - ball.radius)) {
ball.dx *= -1;
}
if(ball.y <= ball.radius ||
ball.y >= (height - ball.radius)) {
ball.dy *= -1;
}
// move ball
ball.x += ball.dx;
ball.y += ball.dy;
// draw it
ctx.arc(ball.x, ball.y, ball.radius, 0, 2*Math.PI, false);
ctx.stroke();
ctx.fill();
}
}
else{
//canvas not supported
}
}
// Calls draw frameRate times a second.
function bounce() {
var frameRate = 60;
setInterval(draw, 1000 / frameRate);
}
body {
font-family: sans-serif;
}
#myCanvas {
float: left;
margin: 0 10px 0 0;
width: 160px;
height: 160px;
border: 1px solid #888;
}
#inputNumBalls {
font-size: 18px;
padding: 5px 8px;
margin: 5px;
text-align: center;
outline: none;
}
.button {
display: inline;
cursor: pointer;
padding: 2px 8px;
border-radius: 5px;
border: 2px solid #888;
}
.button:hover {
background: #ffd;
border-color: #000;
}
#display {
width: 200px;
height: 50px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<canvas id="myCanvas"> Canvas not supported. </canvas>
<div>
Number of balls:
<input type="text" id="inputNumBalls" size="3" />
<div class="button" id="setNumBalls">Set</div>
<div id="display"></div>
</div>