Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Created October 21, 2012 15:32
Show Gist options
  • Save tkojitu/3927285 to your computer and use it in GitHub Desktop.
Save tkojitu/3927285 to your computer and use it in GitHub Desktop.
touch the canvas to ripple.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, width=device-width, target-densitydpi=device-dpi">
<title>Ripple</title>
<style>
canvas {
border: 1px solid #9C9898;
}
</style>
<script>
var circles = [];
function getCanvas() {
return document.getElementById("canvas");
}
window.onload = function() {
initCanvas();
mainloop();
}
function initCanvas() {
var canvas = getCanvas();
canvas.addEventListener("touchstart", onTouchStart, false);
}
function update() {
enlargeCircles();
}
function enlargeCircles() {
var del = -1;
for (var i = 0; i < circles.length; ++i) {
if (enlargeCircle(circles[i])) {
del = i;
}
}
if (del>= 0) {
circles.splice(del, 1);
}
}
function enlargeCircle(circle) {
circle.r += 1;
circle.alpha -= 0.01;
return circle.r > 100;
}
function draw () {
var canvas = getCanvas();
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawCircles(ctx);
}
function drawCircles(ctx) {
for (var i = 0; i < circles.length; ++i) {
drawCircle(ctx, circles[i]);
}
}
function drawCircle(ctx, circle) {
ctx.beginPath();
ctx.arc(circle.center.x, circle.center.y, circle.r, 0, 2 * Math.PI);
ctx.strokeStyle = getCircleColor(circle);
ctx.stroke();
}
function getCircleColor(circle) {
return "rgba(" + circle.rgb + ", " + circle.alpha + ")";
}
function mainloop() {
update();
draw();
window.webkitRequestAnimationFrame(mainloop);
}
function onTouchStart(event) {
var pos = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
var canvas = getCanvas();
pushCircle(transCoord(canvas, pos));
}
function transCoord(elt, pagePos) {
var rect = elt.getBoundingClientRect();
return {
x: pagePos.x - rect.left,
y: pagePos.y - rect.top
};
}
function pushCircle(pos) {
circles.push(newCircle(pos));
}
function newCircle(pos) {
return {
center: {
x: pos.x,
y: pos.y
},
r: 20,
rgb: "0, 0, 255",
alpha: 1.0
};
}
</script>
</head>
<body>
<canvas id='canvas' width=640 height=480></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment