Skip to content

Instantly share code, notes, and snippets.

@pedrogk
Created March 4, 2014 18:28
Show Gist options
  • Save pedrogk/9352563 to your computer and use it in GitHub Desktop.
Save pedrogk/9352563 to your computer and use it in GitHub Desktop.
Código en html y javascript para hacer un canvas con una imagen de fondo con estrellas y una nave espacial que se mueve al detectar un evento touch.
<!DOCTYPE html>
<html>
<head>
<title>Space Canvas</title>
</head>
<body>
<h1>Juego de nave espacial con Canvas</h1>
<canvas id="spaceCanvas" width="300" height="300">
</canvas>
</body>
</html>
<script>
canvas = document.getElementById("spaceCanvas");
ctx = canvas.getContext("2d");
// definimos variables para almacenar imagenes que usaremos.
var oldBackground;
var newBackground;
var ship;
// definimos e inicializamos variables para coordenadas.
var oldX = 0;
var oldY = 0;
var newX = 0;
var newY = 0;
fondo();
nave();
setInterval(gameLoop, 20);
document.addEventListener("touchstart", moverNave, true);
function fondo() {
// Primero lo pintamos negro
ctx.fillStyle = "black";
ctx.rect(0, 0, 300, 300);
ctx.fill();
// Dibujemos 100 estrellas
ctx.fillStyle = "white";
for (i = 0; i <= 100; i++) {
// Generamos coordenadas al azar entre 30 y 299
var x = 30 + Math.floor(Math.random() * 269);
var y = 30 + Math.floor(Math.random() * 269);
// Dibujamos la estrella
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
// inicializamos la imagen de fondo con el estado inicial
newBackground = ctx.getImageData(0, 0, 30, 30);
oldBackground = newBackground;
}
function nave() {
// Dibujemos la nave usando curbas de bezier.
// Primero pintemos el fuselaje en azul
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.beginPath();
ctx.moveTo(28.4, 16.9);
ctx.bezierCurveTo(28.4, 19.7, 22.9, 22.0, 16.0, 22.0);
ctx.bezierCurveTo(9.1, 22.0, 3.6, 19.7, 3.6, 16.9);
ctx.bezierCurveTo(3.6, 14.1, 9.1, 11.8, 16.0, 11.8);
ctx.bezierCurveTo(22.9, 11.8, 28.4, 14.1, 28.4, 16.9);
ctx.closePath();
ctx.fill();
// ahora la cabina en rojo
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.beginPath();
ctx.moveTo(22.3, 12.0);
ctx.bezierCurveTo(22.3, 13.3, 19.4, 14.3, 15.9, 14.3);
ctx.bezierCurveTo(12.4, 14.3, 9.6, 13.3, 9.6, 12.0);
ctx.bezierCurveTo(9.6, 10.8, 12.4, 9.7, 15.9, 9.7);
ctx.bezierCurveTo(19.4, 9.7, 22.3, 10.8, 22.3, 12.0);
ctx.closePath();
ctx.fill();
// guardamos la imagen de la nave
ship = ctx.getImageData(0, 0, 30, 30);
}
function gameLoop() {
ctx.putImageData(oldBackground, oldX, oldY);
ctx.putImageData(ship, newX, newY);
}
function moverNave (event) {
event.preventDefault(); //To prevent default behavior
oldX = newX;
oldY = newY;
oldBackground = newBackground;
ctx.putImageData(oldBackground, oldX,oldY);
var eventTouch;
eventTouch = event.changedTouches[0];
newX = eventTouch.pageX - 15;
newY = eventTouch.pageY - 60;
newBackground = ctx.getImageData(newX, newY, 30, 30);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment