I did a animation using javascript. Using single ball shape goes top of the page. Anybody would help how to create multiple balls like clone.. I just want the following tasks..
Animation with multiple balls (Bottom to top)
Each ball position (Left position only) is random.
Infinite process.
Is it possible to achieve through javascript. Thanks in advance :)
.circle{
width: 50px;
height: 50px;
border-radius: 30px;
position: absolute;
bottom: -60px;
left: 2px;
transition: 0.1s;
}
body{
overflow: hidden;
position: relative;
background: violet
}
#box{
width: 100%;
height: 100%;
}
<body>
<div id="box"></div>
<script type="text/javascript">
var colors = ['red', 'yellow', 'blue', 'green', 'brown', 'violet'];
var windowHeight = 0;
var parendElement;
window.onload = function () {
parendElement = document.getElementById("box");
windowHeight = window.innerHeight;
document.body.style.height = windowHeight + "px";
console.log(document.body.style.height);
generateBall();
};
function generateBall() {
var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
var para = document.createElement("p");
para.setAttribute("class", 'circle');
para.style.background = colors[Math.floor(Math.random() * colors.length)];
para.style.left = leftPos + "px";
parendElement.appendChild(para);
var btmPos = 0;
var animationInterval = setInterval(function () {
if (btmPos < windowHeight) {
btmPos += 5;
} else {
console.log("yes");
clearInterval(animationInterval);
parendElement.removeChild(para);
}
para.style.bottom = btmPos + "px";
para.style.left = leftPos + "px";
}, 100);
}
</script>
</body>
This might help you..
var canvas = {
element: document.getElementById('canvas'),
width: 600,
height: 400,
initialize: function () {
this.element.style.width = this.width + 'px';
this.element.style.height = this.height + 'px';
document.body.appendChild(this.element);
}
};
var Ball = {
create: function (color, dx, dy) {
var newBall = Object.create(this);
newBall.dx = dx;
newBall.dy = dy;
newBall.width = 40;
newBall.height = 40;
newBall.element = document.createElement('div');
newBall.element.style.backgroundColor = color;
newBall.element.style.width = newBall.width + 'px';
newBall.element.style.height = newBall.height + 'px';
newBall.element.className += ' ball';
newBall.width = parseInt(newBall.element.style.width);
newBall.height = parseInt(newBall.element.style.height);
canvas.element.appendChild(newBall.element);
return newBall;
},
moveTo: function (x, y) {
this.element.style.left = x + 'px';
this.element.style.top = y + 'px';
},
changeDirectionIfNecessary: function (x, y) {
if (x < 0 || x > canvas.width - this.width) {
this.dx = -this.dx;
}
if (y < 0 || y > canvas.height - this.height) {
this.dy = -this.dy;
}
},
draw: function (x, y) {
this.moveTo(x, y);
var ball = this;
setTimeout(function () {
ball.changeDirectionIfNecessary(x, y);
ball.draw(x + ball.dx, y + ball.dy);
}, 1000 / 60);
}
};
canvas.initialize();
var ball1 = Ball.create("blue", 4, 3);
var ball2 = Ball.create("red", 1, 5);
var ball3 = Ball.create("green", 2, 2);
ball1.draw(70, 0);
ball2.draw(20, 200);
ball3.draw(300, 330);
body {
text-align: center;
}
#canvas {
position: relative;
background-color: #ccddcc;
margin: 1em auto;
}
.ball {
background-color: black;
position: absolute;
display: inline-block;
border-radius: 50%;
}
<h1>Bouncing Balls</h1>
<p>These bouncing balls are made with completely raw JavaScript,
just with divs. We don't use jQuery. We don't use canvas.</p>
<div id="canvas"></div>
Just add this code
var interval = setInterval(function () {
generateBall();
}, 1000);
into your window.onload(). It works :) ..
.circle{
width: 50px;
height: 50px;
border-radius: 30px;
position: absolute;
bottom: -60px;
left: 2px;
transition: 0.1s;
}
body{
overflow: hidden;
position: relative;
background: violet
}
#box{
width: 100%;
height: 100%;
}
<body>
<div id="box"></div>
<script type="text/javascript">
var colors = ['red', 'yellow', 'blue', 'green', 'brown', 'violet'];
var windowHeight = 0;
var parendElement;
window.onload = function () {
parendElement = document.getElementById("box");
windowHeight = window.innerHeight;
document.body.style.height = windowHeight + "px";
console.log(document.body.style.height);
generateBall();
//Creates ball for every 1 second interval
var interval = setInterval(function () {
generateBall();
}, 1000);
};
function generateBall() {
var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
var para = document.createElement("p");
para.setAttribute("class", 'circle');
para.style.background = colors[Math.floor(Math.random() * colors.length)];
para.style.left = leftPos + "px";
parendElement.appendChild(para);
var btmPos = 0;
var animationInterval = setInterval(function () {
if (btmPos < windowHeight) {
btmPos += 5;
} else {
console.log("yes");
clearInterval(animationInterval);
parendElement.removeChild(para);
}
para.style.bottom = btmPos + "px";
para.style.left = leftPos + "px";
}, 100);
}
</script>
</body>
Related
I'm trying to make a cursor that leaves a trail of magic dust like in that intro to any Disney film: example. So the way I see it is it's split into two parts. 1. the trail and 2. similar trail that falls and fades out. So far I have made the basic trail work quite well, the code below is for the falling trail and essentially a copy of it with a css animation..
The problem I'm having is it's jittering a lot. I'm guessing the css animation is not great for performance and is causing this to really jitter on my page. I've just read up on requestAnimationFrame but am new to this so not sure how to implement it.. How could I use requestAnimationFrame instead of css here?
I also think creating the animation custom in js would allow there to also be a random offset in the animation of the falling particles.. much more like in the video.
window.addEventListener('mousemove', function (e) {
//trail
[1, .9, .8, .5, .25, .6, .4, .3, .2].forEach(function (i) {
var j = (1 - i) * 50;
var elem = document.createElement('div');
var size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.position = 'fixed';
elem.style.zIndex = 6;
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.opacity = "0.5";
elem.style.height = size;
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
elem.style.borderRadius = size;
elem.style.pointerEvents = 'none';
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
});
// falling trail
[1, .9, .8, .5, .25, .6, .3, .2].forEach(function (i) {
var j = (1 - i) * 50;
var elem = document.createElement('div');
var size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.position = 'fixed';
elem.style.zIndex = 6;
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.opacity = "0.5";
elem.style.height = size;
elem.style.animation = "fallingsparkles 1s";
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
elem.style.borderRadius = size;
elem.style.pointerEvents = 'none';
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
});
}, false);
body {
width:100%;
height:100%;
background-color: #000;
}
#keyframes fallingsparkles {
from {
transform: translateY(0);
}
to {
transform: translateY(50px);
}
}
<body></body>
What a cool little animation. I think it will be annoying in the long run, but still: cool.
What I don't like about this solution is that I had to do a continuous recursive loop, that goes on even if there are no elements to animate. There are probably ways to avoid that, but it would be too complex for just to showcase how to implement requestAnimationFrame. As you can see, it's not that hard to use requestAnimationFrame. You just call the same method that you do the calculations in.
Apart from adding each element to the body, I also added the element into sparkleArr with a few more properties through addAnimationProperties. I finally added a whole new method - moveSparkles - for calculating movement and removing the elements. calculateInterpolation calculates the percentage of how long the element should move, based on when the element was created, when it will disappear and the current time.
I think the code is self-explanatory. I had to do a comment on one place, where I don't think it would be possible to explain the code through variables or method names.
let trailArr = [1, .9, .8, .5, .25, .6, .4, .3, .2];
var sparklesArr = [];
function trailAnimation(e, i, maxYTranslation) {
let elem = document.createElement('div');
elem = styleSparkle(elem, e, i);
elem.classList.add("sparkle");
document.body.appendChild(elem);
elem = addAnimationProperties(elem, i, maxYTranslation);
sparklesArr.push(elem);
}
function styleSparkle(elem, e, i) {
let j = (1 - i) * 50;
let size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.height = size;
elem.style.borderRadius = size;
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
return elem;
}
function addAnimationProperties(elem, i, maxYTranslation) {
const ANIMATION_SPEED = 1100;
let lifeExpectancy = Math.round(Math.random() * i * ANIMATION_SPEED);
elem.maxYTranslation = maxYTranslation;
elem.animationSpeed = ANIMATION_SPEED;
elem.created = Date.now();
elem.diesAt = elem.created + lifeExpectancy;
return elem;
}
function moveSparkles() {
let remove = false;
let moveIndex = 0;
let sparkle;
for (let i = 0; i < sparklesArr.length; i++) {
sparkle = sparklesArr[i];
remove = sparkle.diesAt <= Date.now();
if (remove) {
document.body.removeChild(sparkle);
} else {
if (sparkle.maxYTranslation) {
let interpolation = calculateInterpolation(sparkle);
sparkle.style.transform = `translateY(${interpolation}px)`;
}
sparklesArr[moveIndex++] = sparkle; // faster than array.splice()
}
}
sparklesArr.length = moveIndex;
requestAnimationFrame(moveSparkles);
}
function calculateInterpolation(sparkle) {
let currentMillis = Date.now();
let lifeProgress = (currentMillis - sparkle.created) / sparkle.animationSpeed;
let interpolation = sparkle.maxYTranslation * lifeProgress;
return interpolation;
}
window.addEventListener('mousemove', function (e) {
trailArr.forEach((i) => {trailAnimation(e, i)});
let maxYTranslation = '80';
trailArr.forEach((i) => {trailAnimation(e, i, maxYTranslation)});
}, false);
moveSparkles(); // starts the recursive loop
body {
width:100%;
height:100%;
background-color: #000;
}
.sparkle {
position: fixed;
z-index: 6;
opacity: 0.5;
pointer-events: none;
}
<body></body>
I made another version thats quite fun.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
width: 100%;
height: 100%;
background-color: #000;
}
.star-five {
background: transparent;
margin: 50px 0;
position: relative;
display: block;
color: #ffffff;
width: 0px;
height: 0px;
border-right: 100px solid transparent;
border-bottom: 70px solid #ffffff;
border-left: 100px solid transparent;
/* transform: rotate(35deg) scale(0.1) translate(-1450px, -250px); */
}
.star-five:before {
border-bottom: 80px solid #ffffff;
border-left: 30px solid transparent;
border-right: 30px solid transparent;
background-color: transparent;
position: absolute;
height: 0;
width: 0;
top: -45px;
left: -65px;
display: block;
content: '';
transform: rotate(-35deg);
}
.star-five:after {
background-color: transparent;
position: absolute;
display: block;
color: #ffffff;
top: 3px;
left: -105px;
width: 0px;
height: 0px;
border-right: 100px solid transparent;
border-bottom: 70px solid #ffffff;
border-left: 100px solid transparent;
transform: rotate(-70deg);
content: '';
}
</style>
</head>
<body>
<script>
window.addEventListener('mousemove', function (e) {
//trail
[.7, .9, .8, .5, .25, .6, .4, .3, .2].forEach(function (i) {
var j = (1 - i) * 50;
var elem = document.createElement('div');
var size = Math.ceil(Math.random() * 10 * i) + 'px';
//ramdom number between 0 and 1
var precision = 50; // 2 decimals
var randomnum = Math.floor(Math.random() * (10 * precision - 1 * precision) + 1 * precision) / (1*precision);
var rOpacity = randomnum/10;
var rSize = randomnum/120;
elem.style.position = 'fixed';
elem.classList.add('star-five')
elem.style.zIndex = 6;
elem.style.transform = `rotate(35deg) scale(${rSize})`
//elem.style.transform = `rotate(35deg) scale(${rSize}) translate(-1450px, -250px)`
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) - 100 + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) - 100 + 'px';
//elem.style.width = size;
//console.log(rSize);
elem.style.opacity = rOpacity;
//elem.style.height = size;
// elem.style.background = 'hsla(' +
// Math.round(Math.random() * 160) + ', ' +
// '60%, ' +
// '100%, ' +
// i + ')';
//elem.style.borderRadius = size;
elem.style.pointerEvents = 'none';
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
});
////
}, false);
</script>
</body>
</html>
I'm mostly posting this for others to use, where I refactored the code a bit. Nothing has changed, but it's easier to follow. I will follow up with a real answer.
let trailArr = [1, .9, .8, .5, .25, .6, .4, .3, .2];
function trailAnimation(e, i, callbackFn) {
var elem = document.createElement('div');
elem = styleSparkle(elem, e, i);
if (typeof callbackFn == 'function') {
elem = callbackFn(elem);
}
elem.classList.add("sparkle");
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
}
function styleSparkle(elem, e, i) {
let j = (1 - i) * 50;
let size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.height = size;
elem.style.borderRadius = size;
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
return elem;
}
window.addEventListener('mousemove', function (e) {
trailArr.forEach((i) => {trailAnimation(e, i)});
trailArr.forEach((i) => {trailAnimation(e, i, (elem) => {
elem.style.animation = "fallingsparkles 1s";
return elem;
})});
}, false);
body {
width:100%;
height:100%;
background-color: #000;
}
.sparkle {
position: fixed;
z-index: 6;
opacity: 0.5;
pointer-events: none;
}
#keyframes fallingsparkles {
from {
transform: translateY(0);
}
to {
transform: translateY(50px);
}
}
<body></body>
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've put together a simple jQuery script to create a radial gradient that follows the mouse with a delay, but since it's in a mousemove function, when the mouse stops moving the gradient doesn't catch up. Is there a simple way to make the gradient catch up with the mouse when the mouse stops without writing a function that's constantly running?
var xPos = 0;
var yPos = 0;
var dX = 0;
var dY = 0;
var repeater;
$(document).mousemove(function(event) {
windowWidth = $(window).width();
windowHeight = $(window).height();
mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);
dX = mouseXpercentage - xPos;
dY = mouseYpercentage - yPos;
xPos += (dX / 50);
yPos += (dY / 50);
$('.rgradient').css('background', 'radial-gradient(at ' + xPos + '% ' + yPos + '%, #e6e6e6, #1e1e1e)');
});
.rgradient {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #1e1e1e;
background: radial-gradient( at center, #e6e6e6 #1e1e1e);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rgradient"></div>
You can use requestAnimationFrame(), as it only runs once for each frame:
var xPos = 0;
var yPos = 0;
var dX = 0;
var dY = 0;
var mouseRaf = null;
var gradMoveRaf = null;
$(document).mousemove(function(event) {
if (!mouseRaf) {
mouseRaf = requestAnimationFrame(function() {
windowWidth = $(window).width();
windowHeight = $(window).height();
mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);
dX = mouseXpercentage - xPos;
dY = mouseYpercentage - yPos;
mouseRaf = null;
});
}
if (!gradMoveRaf) {
gradMoveRaf = requestAnimationFrame(gradMove);
}
});
function gradMove() {
xPos += (dX / 50);
yPos += (dY / 50);
$('.rgradient').css('background', 'radial-gradient(at ' + xPos + '% ' + yPos + '%, #e6e6e6, #1e1e1e)');
var absX = Math.abs(mouseXpercentage - xPos);
var absY = Math.abs(mouseYpercentage - yPos);
if (absX < 1 && absY < 1) {
gradMoveRaf = null;
console.log("stop");
} else {
gradMoveRaf = requestAnimationFrame(gradMove);
console.log("repeat");
}
}
.rgradient {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #1e1e1e;
background: radial-gradient(at center, #e6e6e6 #1e1e1e);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rgradient"></div>
I have the following canvas:
Codepen link
What I want: Equal margin on both sides of canvas without any horizontal scroll bars.
Problem: margin-right property does not to work. I have seen some solutions that solve this problem by specifying a fixed width, but I cannot have a fixed width in my case. I want my canvas to adjust its width height according to the size of the window.
The following Javascript takes care of that:
window.addEventListener('resize' , resizeCanvas , false);
function resizeCanvas(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight/1.2;
}
So is there a different solution?
For the overflow problem, if I put overflow-x: hidden inside the body then only the scrollbar disappears but the problem persists. The canvas still extends past the screen hence the right border of the canvas is No longer visible.
See here
Here is my code:
HTML
<body onload="start()">
<canvas id="myCanvas"></canvas>
</body>
CSS
body{
}
canvas{
border: 1px solid black;
border-radius: 5px;
background-color: #fff;
margin: auto 50px auto 50px; /* works for left margin but not for right */
}
Thanks!
Another thing:
I have not set width: 100% for the canvas because it distorts the content inside it.
As Chris is saying you need to set the width of the canvas lower than the full width of the page:
canvas.width = window.innerWidth - 100;
Note that you need to take the border-width of the canvas and in your codepen the body also has a margin of 8px into account as well:
canvas.width = window.innerWidth - 118;
CSS calc() method is what you need. Just subtract the margins from 100% and you get the desired result. See the demo below. CSS calc() reference
function start() {
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 1.2;
var ctx = canvas.getContext('2d');
function rand(min, max) {
return parseInt(Math.random() * (max - min + 1), 10) + min;
}
function get_random_color() {
var h = rand(1, 360);
var s = rand(30, 100);
var l = rand(30, 70);
return 'hsl(' + h + ',' + s + '%,' + l + '%)';
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var balls = [];
var ballCount = getRandomInt(2, 10);
//document.getElementById('ballCountInfo').innerHTML = ballCount;
//document.getElementById('box').innerHTML = ballCount;
var startpointX = 100;
var startpointY = 50;
for (var i = 0; i < ballCount; i++) {
var randValue = getRandomInt(20, 30);
balls.push({
x: startpointX,
y: startpointY,
vx: getRandomInt(3, 3) * direction(),
vy: getRandomInt(1, 1) * direction(),
radius: randValue,
mass: randValue,
color: get_random_color(),
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
});
startpointX = startpointX + 50;
startpointY = startpointY + 40;
}
function direction() {
var chosenValue = Math.random() < 0.5 ? 1 : -1;
return chosenValue;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < ballCount; i++) {
balls[i].draw();
balls[i].x += balls[i].vx;
balls[i].y += balls[i].vy;
if ((balls[i].y + balls[i].vy + balls[i].radius) > canvas.height || (balls[i].y + balls[i].vy - balls[i].radius) < 0) {
balls[i].vy = -balls[i].vy;
}
if ((balls[i].x + balls[i].vx + balls[i].radius) > canvas.width || (balls[i].x + balls[i].vx - balls[i].radius) < 0) {
balls[i].vx = -balls[i].vx;
}
}
// onBoxTouched();
//collision check
for (var i = 0; i < ballCount; i++) {
for (var j = i + 1; j < ballCount; j++) {
var distance = Math.sqrt(
(balls[i].x - balls[j].x) * (balls[i].x - balls[j].x) +
(balls[i].y - balls[j].y) * (balls[i].y - balls[j].y)
);
if (distance < (balls[i].radius + balls[j].radius)) {
var ax = (balls[i].vx * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vx)) / (balls[i].mass + balls[j].mass);
var ay = (balls[i].vy * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vy)) / (balls[i].mass + balls[j].mass);
balls[j].vx = (balls[j].vx * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vx)) / (balls[i].mass + balls[j].mass);
balls[j].vy = (balls[j].vy * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vy)) / (balls[i].mass + balls[j].mass);
balls[i].vx = ax;
balls[i].vy = ay;
}
}
}
raf = window.requestAnimationFrame(draw);
}
function onBoxTouched() {
for (var i = 0; i < ballCount; i++) {
if (balls[i].x + balls[i].radius > 600 && balls[i].x + balls[i].radius < 750 &&
balls[i].y + balls[i].radius > 200 && balls[i].y + balls[i].radius < 350) {
//var ele = document.getElementById("box");
ele.style.backgroundColor = balls[i].color;
balls.splice(i, 1);
ballCount = ballCount - 1;
if (ballCount == 0) {
ele.style.fontSize = "x-large";
ele.innerHTML = "Over";
} else {
ele.innerHTML = ballCount;
}
//document.getElementById('ballCountInfo').innerHTML=" "+ballCount;
}
}
}
window.requestAnimationFrame(draw);
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 1.2;
}
}
* {}
html,
body {}
canvas {
border: 1px solid black;
border-radius: 5px;
background-color: #fff;
width: calc(100% - 40px);
/*substract the total margin from 100% and will automoatically adjuts accordint to your need*/
margin: auto 20px auto 20px;
/* works for left margin but not for right */
}
#box {
width: 150px;
height: 150px;
background-color: plum;
border-radius: 5px;
position: absolute;
top: 200px;
left: 600px;
font-size: 72px;
font-weight: bold;
color: white;
line-height: 150px;
text-align: center;
}
#info {
float: left;
font-size: 24px;
color: #6D8390;
margin-top: 20px;
}
<body onload="start()">
<canvas id="myCanvas"></canvas>
</body>
Hope it helps :)
instead of messing around with margins, just change the width of your canvas and center it.
CSS
canvas {
border: 1px solid black;
border-radius: 5px;
background-color: #fff;
width: 90%!important;
}
HTML
<body onload="start()">
<center>
<canvas id="myCanvas"></canvas>
</center>
</body>
https://codepen.io/anon/pen/GEmLPL
I'm doing this assignment where I have to use pure javascript to make a div appear from the side of the screen without having the browser expand. This is what I have so far:
function moveImg() {
var div = document.getElementsByTagName('div')[0];
var pos = 500;
var id = setInterval(Move, 500);
function Move() {
if (pos <= 0) {
clearInterval(id);
} else {
pos++;
div.style.right = pos + 'px';
div.style.top = pos + 'px';
}
}
}
moveImg()
div {
width: 50px;
height: 50px;
background: tomato;
}
<div></div>
I'd use transform generally.
I've done some maths too, I've commented to code but feel free to ask if there's anything you need help understanding.
function moveImg() {
var div = document.getElementsByTagName('div')[0];
var posX = document.body.clientWidth - div.offsetWidth; // start position for X
var posY = document.body.clientHeight - div.offsetHeight; // start position for Y
var tarX = posX / 2; // end position for X
var tarY = posY / 2; // end position for Y
var time = 5; // how many seconds should the animation take
var fps = 60; // frames per second, heigher is smoother but requires more power
var stepX = ((posX - tarX) / (time * fps)); // how far X should move each frame
var stepY = ((posY - tarY) / (time * fps)); // how far Y should move each frame
var id = setInterval(Move, (1000 / fps));
div.style.transform = "translate(" + posX + "px, " + posY + "px)";
div.style.opacity = "1";
function Move() {
if (posX <= tarX && posY <= tarY) {
clearInterval(id);
} else {
posX -= stepX;
posY -= stepY;
div.style.transform = "translate(" + posX + "px, " + posY + "px)";
}
}
}
moveImg();
body {
margin: 0;
width: 100vw;
height: 100vh;
}
div {
display: inline-block;
color: white;
padding: 15px 30px;
background: tomato;
opacity: 0;
}
<div>Example!</div>
Like what was said in the comments, you don't say in what direction you want your div to move, nor from which position it should start.
I've set the starting position of top:100, left:100 and reducing the top and left values by 1px each second:
function moveImg() {
var div = document.getElementsByTagName('div')[0];
var pos = 100;
var id = setInterval(Move, 500);
function Move() {
if (pos <= 0) {
clearInterval(id);
} else {
pos--;
div.style.left = pos + 'px';
div.style.top = pos + 'px';
}
}
}
moveImg()
div {
width: 50px;
height: 50px;
background: tomato;
position: relative;
top: 100px;
left: 100px;
}
<div></div>