Skip to content

Instantly share code, notes, and snippets.

@threez
Created April 23, 2011 18:53
Show Gist options
  • Save threez/938871 to your computer and use it in GitHub Desktop.
Save threez/938871 to your computer and use it in GitHub Desktop.
BouncingHearts in HTML/CSS/JS
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="screen">
* {
overflow: hidden;
font-family: "Helvetica Neue";
cursor: pointer;
text-selection: none;
}
span.heart {
position: absolute;
color: red;
}
</style>
<script type="text/javascript" charset="utf-8">
// returns the hex color for the passed decimal number
function hexColor(color) {
color = Math.floor(color).toString(16);
return color.length == 1 ? "0" + color: color;
}
// returns the read color for the passed rgb fraction (value: 0 - 255)
function redColor(value) {
return "#" + hexColor(value) + "0000";
}
// Heart class represents a beating heart. It is implemented using a span
// and a heart character. Coloring and resizing the span to create the
// effect
var Heart = function(x, y) {
this.initalize(x, y);
};
Heart.prototype = {
initalize: function(x, y) {
// create an element
this.element = document.createElement("span");
this.element.className = "heart";
this.element.style.top = y + "px";
this.element.style.left = x + "px";
// randomly different heart style
this.element.innerText = (Math.random() > 0.5) ? "\u2661" : "\u2665";
// initial sin
this.heartBeat = 0;
},
// makes the heart beating
update: function() {
this.heartBeat += 0.05;
var current = Math.abs(Math.sin(this.heartBeat));
this.element.style.fontSize = (current * 100) + "px";
this.element.style.color = redColor(current * 255);
}
};
var hearts = [];
window.onload = function() {
var screen = document.getElementById("screen");
// register on click to create a new heart
document.onclick = function(event) {
var heart = new Heart(event.clientX, event.clientY);
hearts.push(heart);
screen.appendChild(heart.element);
};
// update all hearts
setInterval(function() {
for(var i = 0, len = hearts.length; i < len; ++i) hearts[i].update();
}, 20);
};
</script>
</head>
<body id="screen">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment