I use this SVG Pie Chart on my website. It has a pretty animation on load (as you can see by running the snippet below) but I don't want it to be visible by default. I want it show up with its animation on a button click after the page is loaded.
Its probably controlled by triggerAnimation(); function in pie.js but it gets called automatically when the page is loaded as the script is external.
<!-- Pie chart JS-->
<script src="js/pie.js"></script>
How can I control the function from a button click? Help would be appreciated.
Below is a live snippet of the pie chart :
PIE.js, PIE.css and PIE.html
$(function(){
$("#pieChart").drawPieChart([
{ title: "Tokyo", value : 180, color: "#02B3E7" },
{ title: "San Francisco", value: 60, color: "#CFD3D6" },
{ title: "London", value : 50, color: "#736D79" },
{ title: "New York", value: 30, color: "#776068" },
{ title: "Sydney", value : 20, color: "#EB0D42" },
{ title: "Berlin", value : 20, color: "#FFEC62" },
{ title: "Osaka", value : 7, color: "#04374E" }
]);
});
/*!
* jquery.drawPieChart.js
* Version: 0.3(Beta)
* Inspired by Chart.js(http://www.chartjs.org/)
*
* Copyright 2013 hiro
* https://github.com/githiro/drawPieChart
* Released under the MIT license.
*/
;(function($, undefined) {
$.fn.drawPieChart = function(data, options) {
var $this = this,
W = $this.width(),
H = $this.height(),
centerX = W/2,
centerY = H/2,
cos = Math.cos,
sin = Math.sin,
PI = Math.PI,
settings = $.extend({
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 1,
baseColor: "#fff",
baseOffset: 15,
edgeOffset: 30,//offset from edge of $this
pieSegmentGroupClass: "pieSegmentGroup",
pieSegmentClass: "pieSegment",
lightPiesOffset: 12,//lighten pie's width
lightPiesOpacity: .3,//lighten pie's default opacity
lightPieClass: "lightPie",
animation : true,
animationSteps : 90,
animationEasing : "easeInOutExpo",
tipOffsetX: -15,
tipOffsetY: -45,
tipClass: "pieTip",
beforeDraw: function(){ },
afterDrawed : function(){ },
onPieMouseenter : function(e,data){ },
onPieMouseleave : function(e,data){ },
onPieClick : function(e,data){ }
}, options),
animationOptions = {
linear : function (t){
return t;
},
easeInOutExpo: function (t) {
var v = t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t;
return (v>1) ? 1 : v;
}
},
requestAnimFrame = function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
}();
var $wrapper = $('<svg width="' + W + '" height="' + H + '" viewBox="0 0 ' + W + ' ' + H + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>').appendTo($this);
var $groups = [],
$pies = [],
$lightPies = [],
easingFunction = animationOptions[settings.animationEasing],
pieRadius = Min([H/2,W/2]) - settings.edgeOffset,
segmentTotal = 0;
//Draw base circle
var drawBasePie = function(){
var base = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
var $base = $(base).appendTo($wrapper);
base.setAttribute("cx", centerX);
base.setAttribute("cy", centerY);
base.setAttribute("r", pieRadius+settings.baseOffset);
base.setAttribute("fill", settings.baseColor);
}();
//Set up pie segments wrapper
var pathGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var $pathGroup = $(pathGroup).appendTo($wrapper);
$pathGroup[0].setAttribute("opacity",0);
//Set up tooltip
var $tip = $('<div class="' + settings.tipClass + '" />').appendTo('body').hide(),
tipW = $tip.width(),
tipH = $tip.height();
for (var i = 0, len = data.length; i < len; i++){
segmentTotal += data[i].value;
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute("data-order", i);
g.setAttribute("class", settings.pieSegmentGroupClass);
$groups[i] = $(g).appendTo($pathGroup);
$groups[i]
.on("mouseenter", pathMouseEnter)
.on("mouseleave", pathMouseLeave)
.on("mousemove", pathMouseMove)
.on("click", pathClick);
var p = document.createElementNS('http://www.w3.org/2000/svg', 'path');
p.setAttribute("stroke-width", settings.segmentStrokeWidth);
p.setAttribute("stroke", settings.segmentStrokeColor);
p.setAttribute("stroke-miterlimit", 2);
p.setAttribute("fill", data[i].color);
p.setAttribute("class", settings.pieSegmentClass);
$pies[i] = $(p).appendTo($groups[i]);
var lp = document.createElementNS('http://www.w3.org/2000/svg', 'path');
lp.setAttribute("stroke-width", settings.segmentStrokeWidth);
lp.setAttribute("stroke", settings.segmentStrokeColor);
lp.setAttribute("stroke-miterlimit", 2);
lp.setAttribute("fill", data[i].color);
lp.setAttribute("opacity", settings.lightPiesOpacity);
lp.setAttribute("class", settings.lightPieClass);
$lightPies[i] = $(lp).appendTo($groups[i]);
}
settings.beforeDraw.call($this);
//Animation start
triggerAnimation();
function pathMouseEnter(e){
var index = $(this).data().order;
$tip.text(data[index].title + ": " + data[index].value).fadeIn(200);
if ($groups[index][0].getAttribute("data-active") !== "active"){
$lightPies[index].animate({opacity: .8}, 180);
}
settings.onPieMouseenter.apply($(this),[e,data]);
}
function pathMouseLeave(e){
var index = $(this).data().order;
$tip.hide();
if ($groups[index][0].getAttribute("data-active") !== "active"){
$lightPies[index].animate({opacity: settings.lightPiesOpacity}, 100);
}
settings.onPieMouseleave.apply($(this),[e,data]);
}
function pathMouseMove(e){
$tip.css({
top: e.pageY + settings.tipOffsetY,
left: e.pageX - $tip.width() / 2 + settings.tipOffsetX
});
}
function pathClick(e){
var index = $(this).data().order;
var targetGroup = $groups[index][0];
for (var i = 0, len = data.length; i < len; i++){
if (i === index) continue;
$groups[i][0].setAttribute("data-active","");
$lightPies[i].css({opacity: settings.lightPiesOpacity});
}
if (targetGroup.getAttribute("data-active") === "active"){
targetGroup.setAttribute("data-active","");
$lightPies[index].css({opacity: .8});
} else {
targetGroup.setAttribute("data-active","active");
$lightPies[index].css({opacity: 1});
}
settings.onPieClick.apply($(this),[e,data]);
}
function drawPieSegments (animationDecimal){
var startRadius = -PI/2,//-90 degree
rotateAnimation = 1;
if (settings.animation) {
rotateAnimation = animationDecimal;//count up between0~1
}
$pathGroup[0].setAttribute("opacity",animationDecimal);
//draw each path
for (var i = 0, len = data.length; i < len; i++){
var segmentAngle = rotateAnimation * ((data[i].value/segmentTotal) * (PI*2)),//start radian
endRadius = startRadius + segmentAngle,
largeArc = ((endRadius - startRadius) % (PI * 2)) > PI ? 1 : 0,
startX = centerX + cos(startRadius) * pieRadius,
startY = centerY + sin(startRadius) * pieRadius,
endX = centerX + cos(endRadius) * pieRadius,
endY = centerY + sin(endRadius) * pieRadius,
startX2 = centerX + cos(startRadius) * (pieRadius + settings.lightPiesOffset),
startY2 = centerY + sin(startRadius) * (pieRadius + settings.lightPiesOffset),
endX2 = centerX + cos(endRadius) * (pieRadius + settings.lightPiesOffset),
endY2 = centerY + sin(endRadius) * (pieRadius + settings.lightPiesOffset);
var cmd = [
'M', startX, startY,//Move pointer
'A', pieRadius, pieRadius, 0, largeArc, 1, endX, endY,//Draw outer arc path
'L', centerX, centerY,//Draw line to the center.
'Z'//Cloth path
];
var cmd2 = [
'M', startX2, startY2,
'A', pieRadius + settings.lightPiesOffset, pieRadius + settings.lightPiesOffset, 0, largeArc, 1, endX2, endY2,//Draw outer arc path
'L', centerX, centerY,
'Z'
];
$pies[i][0].setAttribute("d",cmd.join(' '));
$lightPies[i][0].setAttribute("d", cmd2.join(' '));
startRadius += segmentAngle;
}
}
var animFrameAmount = (settings.animation)? 1/settings.animationSteps : 1,//if settings.animationSteps is 10, animFrameAmount is 0.1
animCount =(settings.animation)? 0 : 1;
function triggerAnimation(){
if (settings.animation) {
requestAnimFrame(animationLoop);
} else {
drawPieSegments(1);
}
}
function animationLoop(){
animCount += animFrameAmount;//animCount start from 0, after "settings.animationSteps"-times executed, animCount reaches 1.
drawPieSegments(easingFunction(animCount));
if (animCount < 1){
requestAnimFrame(arguments.callee);
} else {
settings.afterDrawed.call($this);
}
}
function Max(arr){
return Math.max.apply(null, arr);
}
function Min(arr){
return Math.min.apply(null, arr);
}
return $this;
};
})(jQuery);
.chart {
position: absolute;
width: 250px;
height: 250px;
top: 100%;
left: 50%;
margin: -225px 0 0 -225px;
}
.pieTip {
position: absolute;
float: left;
min-width: 30px;
max-width: 300px;
padding: 5px 18px 6px;
border-radius: 2px;
background: rgba(255,255,255,.97);
color: #444;
font-size: 19px;
text-shadow: 0 1px 0 #fff;
text-transform: uppercase;
text-align: center;
line-height: 1.3;
letter-spacing: .06em;
box-shadow: 0 0 3px rgba(0,0,0,0.2), 0 1px 2px rgba(0,0,0,0.5);
-webkit-transform: all .3s;
-moz-transform: all .3s;
-ms-transform: all .3s;
-o-transform: all .3s;
transform: all .3s;
pointer-events: none;
}
.pieTip:after {
position: absolute;
left: 50%;
bottom: -6px;
content: "";
height: 0;
margin: 0 0 0 -6px;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
border-top: 6px solid rgba(255,255,255,.95);
line-height: 0;
}
.chart path { cursor: pointer; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pieChart" class="chart"></div>
Call .drawPieChart() on button click event:
$(function() {
$('button').click(function() {
// Clean up old chart contents
$("#pieChart").empty();
// Clean up Tooltips created by chart
$('.pieTip').remove();
// Draw a new chart
$("#pieChart").drawPieChart([{
title: "Tokyo",
value: 180,
color: "#02B3E7"
}, {
title: "San Francisco",
value: 60,
color: "#CFD3D6"
}, {
title: "London",
value: 50,
color: "#736D79"
}, {
title: "New York",
value: 30,
color: "#776068"
}, {
title: "Sydney",
value: 20,
color: "#EB0D42"
}, {
title: "Berlin",
value: 20,
color: "#FFEC62"
}, {
title: "Osaka",
value: 7,
color: "#04374E"
}]);
});
});
/*!
* jquery.drawPieChart.js
* Version: 0.3(Beta)
* Inspired by Chart.js(http://www.chartjs.org/)
*
* Copyright 2013 hiro
* https://github.com/githiro/drawPieChart
* Released under the MIT license.
*/
;
(function($, undefined) {
$.fn.drawPieChart = function(data, options) {
var $this = this,
W = $this.width(),
H = $this.height(),
centerX = W / 2,
centerY = H / 2,
cos = Math.cos,
sin = Math.sin,
PI = Math.PI,
settings = $.extend({
segmentShowStroke: true,
segmentStrokeColor: "#fff",
segmentStrokeWidth: 1,
baseColor: "#fff",
baseOffset: 15,
edgeOffset: 30, //offset from edge of $this
pieSegmentGroupClass: "pieSegmentGroup",
pieSegmentClass: "pieSegment",
lightPiesOffset: 12, //lighten pie's width
lightPiesOpacity: .3, //lighten pie's default opacity
lightPieClass: "lightPie",
animation: true,
animationSteps: 90,
animationEasing: "easeInOutExpo",
tipOffsetX: -15,
tipOffsetY: -45,
tipClass: "pieTip",
beforeDraw: function() {},
afterDrawed: function() {},
onPieMouseenter: function(e, data) {},
onPieMouseleave: function(e, data) {},
onPieClick: function(e, data) {}
}, options),
animationOptions = {
linear: function(t) {
return t;
},
easeInOutExpo: function(t) {
var v = t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
return (v > 1) ? 1 : v;
}
},
requestAnimFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
}();
var $wrapper = $('<svg width="' + W + '" height="' + H + '" viewBox="0 0 ' + W + ' ' + H + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>').appendTo($this);
var $groups = [],
$pies = [],
$lightPies = [],
easingFunction = animationOptions[settings.animationEasing],
pieRadius = Min([H / 2, W / 2]) - settings.edgeOffset,
segmentTotal = 0;
//Draw base circle
var drawBasePie = function() {
var base = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
var $base = $(base).appendTo($wrapper);
base.setAttribute("cx", centerX);
base.setAttribute("cy", centerY);
base.setAttribute("r", pieRadius + settings.baseOffset);
base.setAttribute("fill", settings.baseColor);
}();
//Set up pie segments wrapper
var pathGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var $pathGroup = $(pathGroup).appendTo($wrapper);
$pathGroup[0].setAttribute("opacity", 0);
//Set up tooltip
var $tip = $('<div class="' + settings.tipClass + '" />').appendTo('body').hide(),
tipW = $tip.width(),
tipH = $tip.height();
for (var i = 0, len = data.length; i < len; i++) {
segmentTotal += data[i].value;
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute("data-order", i);
g.setAttribute("class", settings.pieSegmentGroupClass);
$groups[i] = $(g).appendTo($pathGroup);
$groups[i]
.on("mouseenter", pathMouseEnter)
.on("mouseleave", pathMouseLeave)
.on("mousemove", pathMouseMove)
.on("click", pathClick);
var p = document.createElementNS('http://www.w3.org/2000/svg', 'path');
p.setAttribute("stroke-width", settings.segmentStrokeWidth);
p.setAttribute("stroke", settings.segmentStrokeColor);
p.setAttribute("stroke-miterlimit", 2);
p.setAttribute("fill", data[i].color);
p.setAttribute("class", settings.pieSegmentClass);
$pies[i] = $(p).appendTo($groups[i]);
var lp = document.createElementNS('http://www.w3.org/2000/svg', 'path');
lp.setAttribute("stroke-width", settings.segmentStrokeWidth);
lp.setAttribute("stroke", settings.segmentStrokeColor);
lp.setAttribute("stroke-miterlimit", 2);
lp.setAttribute("fill", data[i].color);
lp.setAttribute("opacity", settings.lightPiesOpacity);
lp.setAttribute("class", settings.lightPieClass);
$lightPies[i] = $(lp).appendTo($groups[i]);
}
settings.beforeDraw.call($this);
//Animation start
triggerAnimation();
function pathMouseEnter(e) {
var index = $(this).data().order;
$tip.text(data[index].title + ": " + data[index].value).fadeIn(200);
if ($groups[index][0].getAttribute("data-active") !== "active") {
$lightPies[index].animate({
opacity: .8
}, 180);
}
settings.onPieMouseenter.apply($(this), [e, data]);
}
function pathMouseLeave(e) {
var index = $(this).data().order;
$tip.hide();
if ($groups[index][0].getAttribute("data-active") !== "active") {
$lightPies[index].animate({
opacity: settings.lightPiesOpacity
}, 100);
}
settings.onPieMouseleave.apply($(this), [e, data]);
}
function pathMouseMove(e) {
$tip.css({
top: e.pageY + settings.tipOffsetY,
left: e.pageX - $tip.width() / 2 + settings.tipOffsetX
});
}
function pathClick(e) {
var index = $(this).data().order;
var targetGroup = $groups[index][0];
for (var i = 0, len = data.length; i < len; i++) {
if (i === index) continue;
$groups[i][0].setAttribute("data-active", "");
$lightPies[i].css({
opacity: settings.lightPiesOpacity
});
}
if (targetGroup.getAttribute("data-active") === "active") {
targetGroup.setAttribute("data-active", "");
$lightPies[index].css({
opacity: .8
});
} else {
targetGroup.setAttribute("data-active", "active");
$lightPies[index].css({
opacity: 1
});
}
settings.onPieClick.apply($(this), [e, data]);
}
function drawPieSegments(animationDecimal) {
var startRadius = -PI / 2, //-90 degree
rotateAnimation = 1;
if (settings.animation) {
rotateAnimation = animationDecimal; //count up between0~1
}
$pathGroup[0].setAttribute("opacity", animationDecimal);
//draw each path
for (var i = 0, len = data.length; i < len; i++) {
var segmentAngle = rotateAnimation * ((data[i].value / segmentTotal) * (PI * 2)), //start radian
endRadius = startRadius + segmentAngle,
largeArc = ((endRadius - startRadius) % (PI * 2)) > PI ? 1 : 0,
startX = centerX + cos(startRadius) * pieRadius,
startY = centerY + sin(startRadius) * pieRadius,
endX = centerX + cos(endRadius) * pieRadius,
endY = centerY + sin(endRadius) * pieRadius,
startX2 = centerX + cos(startRadius) * (pieRadius + settings.lightPiesOffset),
startY2 = centerY + sin(startRadius) * (pieRadius + settings.lightPiesOffset),
endX2 = centerX + cos(endRadius) * (pieRadius + settings.lightPiesOffset),
endY2 = centerY + sin(endRadius) * (pieRadius + settings.lightPiesOffset);
var cmd = [
'M', startX, startY, //Move pointer
'A', pieRadius, pieRadius, 0, largeArc, 1, endX, endY, //Draw outer arc path
'L', centerX, centerY, //Draw line to the center.
'Z' //Cloth path
];
var cmd2 = [
'M', startX2, startY2,
'A', pieRadius + settings.lightPiesOffset, pieRadius + settings.lightPiesOffset, 0, largeArc, 1, endX2, endY2, //Draw outer arc path
'L', centerX, centerY,
'Z'
];
$pies[i][0].setAttribute("d", cmd.join(' '));
$lightPies[i][0].setAttribute("d", cmd2.join(' '));
startRadius += segmentAngle;
}
}
var animFrameAmount = (settings.animation) ? 1 / settings.animationSteps : 1, //if settings.animationSteps is 10, animFrameAmount is 0.1
animCount = (settings.animation) ? 0 : 1;
function triggerAnimation() {
if (settings.animation) {
requestAnimFrame(animationLoop);
} else {
drawPieSegments(1);
}
}
function animationLoop() {
animCount += animFrameAmount; //animCount start from 0, after "settings.animationSteps"-times executed, animCount reaches 1.
drawPieSegments(easingFunction(animCount));
if (animCount < 1) {
requestAnimFrame(arguments.callee);
} else {
settings.afterDrawed.call($this);
}
}
function Max(arr) {
return Math.max.apply(null, arr);
}
function Min(arr) {
return Math.min.apply(null, arr);
}
return $this;
};
})(jQuery);
.chart {
position: absolute;
width: 250px;
height: 250px;
top: 100%;
left: 50%;
margin: -225px 0 0 -225px;
}
.pieTip {
position: absolute;
float: left;
min-width: 30px;
max-width: 300px;
padding: 5px 18px 6px;
border-radius: 2px;
background: rgba(255, 255, 255, .97);
color: #444;
font-size: 19px;
text-shadow: 0 1px 0 #fff;
text-transform: uppercase;
text-align: center;
line-height: 1.3;
letter-spacing: .06em;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2), 0 1px 2px rgba(0, 0, 0, 0.5);
-webkit-transform: all .3s;
-moz-transform: all .3s;
-ms-transform: all .3s;
-o-transform: all .3s;
transform: all .3s;
pointer-events: none;
}
.pieTip:after {
position: absolute;
left: 50%;
bottom: -6px;
content: "";
height: 0;
margin: 0 0 0 -6px;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
border-top: 6px solid rgba(255, 255, 255, .95);
line-height: 0;
}
.chart path {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pieChart" class="chart"></div>
<button>Animate</button>
Related
I've made an explosion animation but I can't stop it from executing. I've tried using setInterval but it doesn't seem to work. What might be wrong with this code?
function grow() {
setInterval(function() {
balloon = document.querySelector('.balloon');
balloon.style.width = '200px';
balloon.style.height = '200px';
balloon.style.transition = '3s';
setInterval(function() {
balloon.style.display = 'none';
explode(balloon);
}, 2000);
}, 2000);
};
grow();
var anchors = document.querySelectorAll('.balloon');
function explode(e) {
var x = e.clientX
var y = e.clientY
var c = document.createElement('canvas')
var ctx = c.getContext('2d')
var ratio = window.devicePixelRatio
var particles = []
document.body.appendChild(c)
c.style.position = 'absolute'
c.style.left = (x - 100) + 'px'
c.style.top = (y - 100) + 'px'
c.style.pointerEvents = 'none'
c.style.width = 200 + 'px'
c.style.height = 200 + 'px'
c.width = 200 * ratio
c.height = 200 * ratio
function Particle() {
return {
x: c.width / 2,
y: c.height / 2,
radius: r(20, 30),
color: 'rgb(' + [r(0, 255), r(0, 255), r(0, 255)].join(',') + ')',
rotation: r(0, 360, true),
speed: r(8, 12),
friction: 0.9,
opacity: r(0, 0.5, true),
yVel: 0,
gravity: 0.1
}
}
for (var i = 0; ++i < 25;) {
particles.push(Particle())
}
console.log(particles[0])
function render() {
ctx.clearRect(0, 0, c.width, c.height)
particles.forEach(function(p, i) {
angleTools.moveOnAngle(p, p.speed)
p.opacity -= 0.01
p.speed *= p.friction
p.radius *= p.friction
p.yVel += p.gravity
p.y += p.yVel
if (p.opacity < 0) return
if (p.radius < 0) return
ctx.beginPath()
ctx.globalAlpha = p.opacity
ctx.fillStyle = p.color
ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, false)
ctx.fill()
})
}
;
(function renderLoop() {
requestAnimationFrame(renderLoop)
render()
})()
}
var angleTools = {
getAngle: function(t, n) {
var a = n.x - t.x,
e = n.y - t.y;
return Math.atan2(e, a) / Math.PI * 180
},
getDistance: function(t, n) {
var a = t.x - n.x,
e = t.y - n.y;
return Math.sqrt(a * a + e * e)
},
moveOnAngle: function(t, n) {
var a = this.getOneFrameDistance(t, n);
t.x += a.x, t.y += a.y
},
getOneFrameDistance: function(t, n) {
return {
x: n * Math.cos(t.rotation * Math.PI / 180),
y: n * Math.sin(t.rotation * Math.PI / 180)
}
}
};
function r(a, b, c) {
return parseFloat((Math.random() * ((a ? a : 1) - (b ? b : 0)) + (b ? b : 0)).toFixed(c ? c : 0));
}
body {
margin: 20px;
background: hsl(70, 31%, 85%);
}
.explosion {
position: absolute; // required if positioned on click else 'relative'
width: 600px;
height: 600px;
pointer-events: none; // make it clickable trhough
// particle styling
.particle {
position: absolute; // required
width: 10px;
height: 10px;
border-radius: 50%;
animation: pop 1s reverse forwards; // required
}
}
// animation for particle fly away from the cursor
#keyframes pop {
from {
opacity: 0;
}
to {
top: 50%;
left: 50%;
opacity: 1;
}
}
.balloon {
display: inline-block;
width: 103px;
height: 125px;
background: hsl(215, 50%, 65%);
border-radius: 80%;
position: relative;
box-shadow: inset -10px -10px 0 rgba(0, 0, 0, 0.07);
margin: 20px 30px;
transition: transform 0.5s ease;
z-index: 10;
animation: balloons 4s ease-in-out infinite;
transform-origin: bottom center;
}
#keyframes balloons {
0%,
100% {
transform: translateY(0) rotate(-4deg);
}
50% {
transform: translateY(-25px) rotate(4deg);
}
}
.balloon:before {
content: "▲";
font-size: 20px;
color: hsl(215, 30%, 50%);
display: block;
text-align: center;
width: 100%;
position: absolute;
bottom: -12px;
z-index: -100;
}
<div class="balloon"></div>
setTimeout instead of setInterval
function grow() {
setTimeout(function() {
balloon = document.querySelector('.balloon');
balloon.style.width = '200px';
balloon.style.height = '200px';
balloon.style.transition = '3s';
setTimeout(function() {
balloon.style.display = 'none';
explode(balloon);
}, 2000);
}, 2000);
};
grow();
var anchors = document.querySelectorAll('.balloon');
function explode(e) {
var x = e.clientX
var y = e.clientY
var c = document.createElement('canvas')
var ctx = c.getContext('2d')
var ratio = window.devicePixelRatio
var particles = []
document.body.appendChild(c)
c.style.position = 'absolute'
c.style.left = (x - 100) + 'px'
c.style.top = (y - 100) + 'px'
c.style.pointerEvents = 'none'
c.style.width = 200 + 'px'
c.style.height = 200 + 'px'
c.width = 200 * ratio
c.height = 200 * ratio
function Particle() {
return {
x: c.width / 2,
y: c.height / 2,
radius: r(20, 30),
color: 'rgb(' + [r(0, 255), r(0, 255), r(0, 255)].join(',') + ')',
rotation: r(0, 360, true),
speed: r(8, 12),
friction: 0.9,
opacity: r(0, 0.5, true),
yVel: 0,
gravity: 0.1
}
}
for (var i = 0; ++i < 25;) {
particles.push(Particle())
}
console.log(particles[0])
function render() {
ctx.clearRect(0, 0, c.width, c.height)
particles.forEach(function(p, i) {
angleTools.moveOnAngle(p, p.speed)
p.opacity -= 0.01
p.speed *= p.friction
p.radius *= p.friction
p.yVel += p.gravity
p.y += p.yVel
if (p.opacity < 0) return
if (p.radius < 0) return
ctx.beginPath()
ctx.globalAlpha = p.opacity
ctx.fillStyle = p.color
ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, false)
ctx.fill()
})
}
;
(function renderLoop() {
requestAnimationFrame(renderLoop)
render()
})()
}
var angleTools = {
getAngle: function(t, n) {
var a = n.x - t.x,
e = n.y - t.y;
return Math.atan2(e, a) / Math.PI * 180
},
getDistance: function(t, n) {
var a = t.x - n.x,
e = t.y - n.y;
return Math.sqrt(a * a + e * e)
},
moveOnAngle: function(t, n) {
var a = this.getOneFrameDistance(t, n);
t.x += a.x, t.y += a.y
},
getOneFrameDistance: function(t, n) {
return {
x: n * Math.cos(t.rotation * Math.PI / 180),
y: n * Math.sin(t.rotation * Math.PI / 180)
}
}
};
function r(a, b, c) {
return parseFloat((Math.random() * ((a ? a : 1) - (b ? b : 0)) + (b ? b : 0)).toFixed(c ? c : 0));
}
body {
margin: 20px;
background: hsl(70, 31%, 85%);
}
.explosion {
position: absolute; // required if positioned on click else 'relative'
width: 600px;
height: 600px;
pointer-events: none; // make it clickable trhough
// particle styling
.particle {
position: absolute; // required
width: 10px;
height: 10px;
border-radius: 50%;
animation: pop 1s reverse forwards; // required
}
}
// animation for particle fly away from the cursor
#keyframes pop {
from {
opacity: 0;
}
to {
top: 50%;
left: 50%;
opacity: 1;
}
}
.balloon {
display: inline-block;
width: 103px;
height: 125px;
background: hsl(215, 50%, 65%);
border-radius: 80%;
position: relative;
box-shadow: inset -10px -10px 0 rgba(0, 0, 0, 0.07);
margin: 20px 30px;
transition: transform 0.5s ease;
z-index: 10;
animation: balloons 4s ease-in-out infinite;
transform-origin: bottom center;
}
#keyframes balloons {
0%,
100% {
transform: translateY(0) rotate(-4deg);
}
50% {
transform: translateY(-25px) rotate(4deg);
}
}
.balloon:before {
content: "▲";
font-size: 20px;
color: hsl(215, 30%, 50%);
display: block;
text-align: center;
width: 100%;
position: absolute;
bottom: -12px;
z-index: -100;
}
<div class="balloon"></div>
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 a issue in my canvas. i want to change the color of particles. currently they are in black color. How i can change..?
here is my code please let me know if u have any solution.
I have a issue in my canvas. i want to change the color of particles. currently they are in black color. How i can change..?
here is my code please let me know if u have any solution. http://jsfiddle.net/gbcL0uks/
<head>
<title>
Text Particles
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<link rel="stylesheet" href="https://cdn.bootcss.com/hover.css/2.3.1/css/hover-min.css">
<meta property="og:title" content="Text Particles" />
<meta property="og:description" content="Some cool canvas pixel manipulation" />
<meta property="og:image" content="http://william.hoza.us/images/text-small.png" />
<style>
#import url('https://fonts.googleapis.com/css?family=Bree+Serif');
body {
font-family: 'Bree Serif', serif;
}
.float {
position: absolute;
left: 20px;
}
.menu {
position: absolute;
top: 20px;
right: 20px;
cursor: pointer;
}
.fa-bars {
font-size: 24px;
border: 2px solid #333333;
padding: 12px;
transition: .4s;
}
.fa-bars:hover {
background: #333333;
color: #f7d600;
}
.overlay {
height: 100%;
width: 100%;
position: fixed;
z-index: 1;
top: 0;
left: -100%;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.9);
overflow-x: hidden;
transition: 0.5s;
}
.overlay-content {
position: relative;
top: 50%;
width: 100%;
text-align: center;
margin-top: 30px;
transform: translate(0, -100%);
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 6rem;
color: #818181;
display: inline-block;
transition: 0.3s;
margin: 0 3rem;
}
.overlay a:hover,
.overlay a:focus {
color: #f1f1f1;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 0;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay a {
font-size: 20px
}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 0;
}
}
</style>
</head>
<body style="margin:0px; background:#f7d600;">
<div class="float">
<h1>Herbialis</h1>
</div>
<!-- <div class="menu">
<i class="fa fa-bars"></i>
</div> -->
<div id="myNav" class="overlay">
×
<div class="overlay-content">
About
Products
Contact
</div>
</div>
<div class="menu">
<i class="fa fa-bars" onclick="openNav()"></i>
</div>
<canvas id="canv" onmousemove="canv_mousemove(event);" onmouseout="mx=-1;my=-1;">
you need a canvas-enabled browser, such as Google Chrome
</canvas>
<canvas id="wordCanv" width="500px" height="500px" style="border:1px solid black;display:none;">
</canvas>
<textarea id="wordsTxt" style="position:absolute;left:-100;top:-100;" onblur="init();" onkeyup="init();" onclick="init();"></textarea>
<script type="text/javascript">
var l = document.location + "";
l = l.replace(/%20/g, " ");
var index = l.indexOf('?t=');
if (index == -1) document.location = l + "?t=Hello world";
var pixels = new Array();
var canv = $('canv');
var ctx = canv.getContext('2d');
var wordCanv = $('wordCanv');
var wordCtx = wordCanv.getContext('2d');
var mx = -1;
var my = -1;
var words = "";
var txt = new Array();
var cw = 0;
var ch = 0;
var resolution = 1;
var n = 0;
var timerRunning = false;
var resHalfFloor = 0;
var resHalfCeil = 0;
function canv_mousemove(evt) {
mx = evt.clientX - canv.offsetLeft;
my = evt.clientY - canv.offsetTop;
}
function Pixel(homeX, homeY) {
this.homeX = homeX;
this.homeY = homeY;
this.x = Math.random() * cw;
this.y = Math.random() * ch;
//tmp
this.xVelocity = Math.random() * 10 - 5;
this.yVelocity = Math.random() * 10 - 5;
}
Pixel.prototype.move = function () {
var homeDX = this.homeX - this.x;
var homeDY = this.homeY - this.y;
var homeDistance = Math.sqrt(Math.pow(homeDX, 2) + Math.pow(homeDY, 2));
var homeForce = homeDistance * 0.01;
var homeAngle = Math.atan2(homeDY, homeDX);
var cursorForce = 0;
var cursorAngle = 0;
if (mx >= 0) {
var cursorDX = this.x - mx;
var cursorDY = this.y - my;
var cursorDistanceSquared = Math.pow(cursorDX, 2) + Math.pow(cursorDY, 2);
cursorForce = Math.min(10000 / cursorDistanceSquared, 10000);
cursorAngle = Math.atan2(cursorDY, cursorDX);
} else {
cursorForce = 0;
cursorAngle = 0;
}
this.xVelocity += homeForce * Math.cos(homeAngle) + cursorForce * Math.cos(cursorAngle);
this.yVelocity += homeForce * Math.sin(homeAngle) + cursorForce * Math.sin(cursorAngle);
this.xVelocity *= 0.92;
this.yVelocity *= 0.92;
this.x += this.xVelocity;
this.y += this.yVelocity;
}
function $(id) {
return document.getElementById(id);
}
function timer() {
if (!timerRunning) {
timerRunning = true;
setTimeout(timer, 33);
for (var i = 0; i < pixels.length; i++) {
pixels[i].move();
}
drawPixels();
wordsTxt.focus();
n++;
if (n % 10 == 0 && (cw != document.body.clientWidth || ch != document.body.clientHeight)) body_resize();
timerRunning = false;
} else {
setTimeout(timer, 10);
}
}
function drawPixels() {
var imageData = ctx.createImageData(cw, ch);
var actualData = imageData.data;
var index;
var goodX;
var goodY;
var realX;
var realY;
for (var i = 0; i < pixels.length; i++) {
goodX = Math.floor(pixels[i].x);
goodY = Math.floor(pixels[i].y);
for (realX = goodX - resHalfFloor; realX <= goodX + resHalfCeil && realX >= 0 && realX < cw; realX++) {
for (realY = goodY - resHalfFloor; realY <= goodY + resHalfCeil && realY >= 0 && realY < ch; realY++) {
index = (realY * imageData.width + realX) * 4;
actualData[index + 3] = 255;
}
}
}
imageData.data = actualData;
ctx.putImageData(imageData, 0, 0);
}
function readWords() {
words = $('wordsTxt').value;
txt = words.split('\n');
}
function init() {
readWords();
var fontSize = 200;
var wordWidth = 0;
do {
wordWidth = 0;
fontSize -= 5;
wordCtx.font = fontSize + "px sans-serif";
for (var i = 0; i < txt.length; i++) {
var w = wordCtx.measureText(txt[i]).width;
if (w > wordWidth) wordWidth = w;
}
} while (wordWidth > cw - 50 || fontSize * txt.length > ch - 50)
wordCtx.clearRect(0, 0, cw, ch);
wordCtx.textAlign = "center";
wordCtx.textBaseline = "middle";
for (var i = 0; i < txt.length; i++) {
wordCtx.fillText(txt[i], cw / 2, ch / 2 - fontSize * (txt.length / 2 - (i + 0.5)));
}
var index = 0;
var imageData = wordCtx.getImageData(0, 0, cw, ch);
for (var x = 0; x < imageData.width; x += resolution) //var i=0;i<imageData.data.length;i+=4)
{
for (var y = 0; y < imageData.height; y += resolution) {
i = (y * imageData.width + x) * 4;
if (imageData.data[i + 3] > 128) {
if (index >= pixels.length) {
pixels[index] = new Pixel(x, y);
} else {
pixels[index].homeX = x;
pixels[index].homeY = y;
}
index++;
}
}
}
pixels.splice(index, pixels.length - index);
}
function body_resize() {
cw = document.body.clientWidth;
ch = document.body.clientHeight;
canv.width = cw;
canv.height = ch;
wordCanv.width = cw;
wordCanv.height = ch;
init();
}
wordsTxt.focus();
wordsTxt.value = l.substring(index + 3);
resHalfFloor = Math.floor(resolution / 2);
resHalfCeil = Math.ceil(resolution / 2);
body_resize();
timer();
</script>
<script>
function openNav() {
document.getElementById("myNav").style.left = "0";
}
function closeNav() {
document.getElementById("myNav").style.left = "-100%";
}
</script>
</body>
</html>
Add 3 color components to image data. For example, for orange color:
for (realX = goodX - resHalfFloor; realX <= goodX + resHalfCeil && realX >= 0 && realX < cw; realX++) {
for (realY = goodY - resHalfFloor; realY <= goodY + resHalfCeil && realY >= 0 && realY < ch; realY++) {
index = (realY * imageData.width + realX) * 4;
actualData[index + 0] = 253; // Red component
actualData[index + 1] = 106; // Green component
actualData[index + 2] = 2; // Blue component
actualData[index + 3] = 255;
}
}
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>
I'm developing an app to help autistic children prepare to learn to write. It's very straight forward. They just need to draw a line straight down. I have it working very similar to "connect the dots" where they start at a green light, progress to yellow and then to red. However, on my webpage using a mouse everything works great because the "dots" are "touched" using the mouseover, like so:
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery.jplayer.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var dots = [13, 15, 13, 25, 13, 55, -1, -1,
45, 15, 45, 40, -1, -1,
70, 15, 70, 40, -1, -1,
80, 15, 80, 40, 80, 60, -1, -1];
function contains(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return true;
}
}
return false;
}
function getRandomPoints(totalPoints) {
var indexes = new Array();
for (var i = 0; i < totalPoints; i++) {
var done = false;
while (!done) {
var index = Math.floor(Math.random() * dots.length);
if (index % 2 != 0) {
index++;
if (index > dots.length) {
continue;
}
}
if (!contains(indexes, index)) {
indexes.push(index);
done = true;
}
}
}
return indexes.sort(function(a, b) {
return a - b;
});
}
function displayGrid(ctx) {
var gridSize = 20, width = 900;
for (var ypos = 0; ypos < width; ypos += gridSize) {
ctx.moveTo(0, ypos);
ctx.lineTo(width, ypos);
}
for (var xpos = 0; xpos < width; xpos += gridSize) {
ctx.moveTo(xpos, 0);
ctx.lineTo(xpos, width);
}
ctx.strokeStyle = "#eee";
ctx.lineWidth = .7;
ctx.stroke();
}
function addPoint(index, x1, y1) {
for (var i = 0; i < points.length; i++) {
var x2 = points[i].x, y2 = points[i].y;
var d1 = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
var d2 = radius * 2 + 2;
if (d2 > d1) {
return false;
}
}
points.push({ 'x': x1, 'y': y1, 'index': index });
return true;
}
//Initialization....
var $graph = $('#graph'), gpos = $graph.position();
var $timer = $('#timer');
var points = new Array();
var ctx = $graph.get(0).getContext("2d");
//Parameters...
var indexes = getRandomPoints(7), ratio = 3, hops = 0, point = 0, maxTotalHops = 60, radius = 12;
var lineWidth = 11.5;
var xDisplacement = 0, yDisplacement = 0;
var borderColor = 'rgb(0,102,204)';
//Display the character's fixed lines...
ctx.beginPath();
ctx.translate(xDisplacement, yDisplacement);
ctx.lineWidth = lineWidth;
for (var i = 0; i < dots.length; i += 2) {
var newLine = dots[i] == -1;
if (newLine) {
i += 2;
}
var x = ratio * dots[i], y = ratio * dots[i + 1];
if (hops == 0 && contains(indexes, i)) {
hops++;
ctx.moveTo(x, y);
continue;
}
if (newLine || i == 0) {
ctx.moveTo(x, y);
}
else {
if (hops == 0) {
ctx.lineTo(x, y);
}
else {
ctx.strokeStyle = borderColor;
ctx.stroke();
ctx.beginPath();
if (addPoint(i, x, y)) {
var cx = gpos.left + xDisplacement - radius + 1 + x;
var cy = gpos.top + yDisplacement - radius + 1 + y;
$('<span></span>')
.addClass('circle')
.html(++point)
.data('pos', { 'x': cx, 'y': cy })
.css({ 'top': 0, 'left': 0 })
.insertAfter($graph);
}
}
}
if (hops > maxTotalHops) {
hops = 0;
}
else if (hops > 0) {
hops++;
}
}
ctx.strokeStyle = borderColor;
ctx.stroke();
//Create and initialize hotspots...
var passed = 0;
$('.circle').each(function() {
var pos = $(this).data('pos');
$(this).animate({
left: pos.x,
top: pos.y
}, 700);
}).mousemove(function() { // <====================== this part
var index = parseInt($(this).text());
if (passed != index - 1) {
return;
}
$(this).css({
'color': '#c00',
'font-weight': 'bold'
}).animate({
left: 0,
top: 0,
opacity: 0
}, 1000);
ctx.beginPath();
var start, end, done = passed + 1 == points.length;
if (done) /*The entire hotspots are detected...*/{
start = 0;
end = dots.length - 2;
clearInterval(tid);
$timer.html('Well done, it took ' + $timer.html() + ' seconds!').animate({
left: gpos.left + $graph.width() - $timer.width() - 20
}, 1000);
}
else {
start = passed == 0 ? points[passed].index - 4 : points[passed - 1].index;
end = points[passed].index;
}
for (var i = start; i <= end; i += 2) {
var newLine = dots[i] == -1;
if (newLine) {
i += 2;
}
var x = ratio * dots[i], y = ratio * dots[i + 1];
if (newLine || i == start) {
ctx.moveTo(x, y);
}
else {
ctx.lineTo(x, y);
}
}
ctx.lineWidth = lineWidth;
ctx.strokeStyle = borderColor;
ctx.stroke();
if (done) {
$('.filled').css({
left: gpos.left + xDisplacement + 10,
top: gpos.top + yDisplacement + 150
}).fadeIn('slow');
}
passed++;
});
//Initialize timer...
$timer.css({
top: gpos.top + 10,
left: gpos.left + 10
});
var timer = 0, tid = setInterval(function() {
timer += 30 / 1000;
$timer.html(timer.toFixed(2));
}, 30);
});
</script>
<style type="text/css">
.circle {
background: url('start.png');
width: 24px;
height: 24px;
text-align: center;
font-size: .8em;
line-height: 24px;
display: block;
position: absolute;
cursor: pointer;
color: #333;
z-index: 100;
}
.filled {
background: url('train.gif');
position: absolute;
width: 172px;
height: 251px;
display: none;
}
#timer {
position: absolute;
font-family: Arial;
font-weight: bold;
font-size: 1em;
background: #c00;
color: #fff;
padding: 5px;
text-align: center;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
font-variant: small-caps;
}
#graph {
background: url('vlinesbackground.jpg');
left: 5px;
top: 20px;
position: relative;
border: 1px dotted #ddd;
}
</style>
But I'm trying to replace the mousemove so the app can be used on the iphone. I've worked out everything else but triggering the "dots" and although I've looked at all the touchstart/touchmove info I can google, nothing appears to be working. Suggestions? Thanks!