Quantcast
Channel: El Club del Programador
Viewing all articles
Browse latest Browse all 18

Construyamos un Reloj con las animaciones de HTML5

$
0
0

Hoy en día crear un reloj no es ninguna tarea compleja, de hecho podemos elegir entre infinidad de plugins de JQuery, javascript, e incluso con lenguajes de scripting, cada solución cumple totalmente con lo necesitado, pero aqui os vamos a mostrar una forma bastante original y que hace uso del feature de HTML5, para hacerlo muy vistoso, vamos a ello.

 

Clase Animation.js

Lo primero a tener en cuenta es la utilización de nuestra clase de Animación que previamente hemos comentado y que nos servirá como framework para crear nuestra animación.

Código

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var Animation = function(canvasId){
  this.canvas = document.getElementById(canvasId);
  this.context = this.canvas.getContext("2d");
  this.t = 0;
  this.timeInterval = 0;
  this.startTime = 0;
  this.lastTime = 0;
  this.frame = 0;
  this.animating = false;

  window.requestAnimFrame = (function(callback){
    return window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function(callback){
        window.setTimeout(callback, 1000 / 60);
      };
  })();

  // getter
  // Para obtener el Contexto
  Animation.prototype.getContext = function(){
    return this.context;
  };

  // Para obetener el canvas
  Animation.prototype.getCanvas = function(){
    return this.canvas;
  };

  // Para determinar si se esta ejecutando la animacion
  Animation.prototype.isAnimating = function(){
    return this.animating;
  };

  // Para obtener el frame actual
  Animation.prototype.getFrame = function(){
    return this.frame;
  };

  // Para obtener el intervalo de animacion
  Animation.prototype.getTimeInterval = function(){
    return this.timeInterval;
  };

  // Para obtener el tiempo total de la animacion
  Animation.prototype.getTime = function(){
    return this.t;
  };

  // Para obtener el FPS calculado para la animacion
  Animation.prototype.getFps = function(){
    return this.timeInterval > 0 ? 1000 / this.timeInterval : 0;
  };

  // limpia el canvas
  Animation.prototype.clear = function(){
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  };

  // define el escenario y lo actualiza
  Animation.prototype.setStage = function(func){
    this.stage = func;
  };


  //Nos permite inciar la animacion "seteando" atributos
  Animation.prototype.start = function(){
    this.animating = true;
    var date = new Date();
    this.startTime = date.getTime();
    this.lastTime = this.startTime;
    if (this.stage !== undefined) {
      this.stage();
    }
    this.animationLoop();
  };

  // detiene la animacion
  Animation.prototype.stop = function(){
    this.animating = false;
  };

  //El loop de animacion
  Animation.prototype.animationLoop = function(){
    var that = this;
    this.frame++;
    var date = new Date();
    var thisTime = date.getTime();
    this.timeInterval = thisTime - this.lastTime;
    this.t += this.timeInterval;
    this.lastTime = thisTime;
    if (this.stage !== undefined) {
      this.stage();
    }

    if (this.animating) {
      requestAnimFrame(function(){
        that.animationLoop();
      });
    }
  };
};

 

Recordemos como utilizar la clase

Simplemente os refresco los pasos que debemos seguir para implementar la animación con nuestra clase:

  • Importar nuestra clase como una librería de javascript en nuestra aplicación HTML5.
  • Definir los valores iniciales para nuestro objeto.
  • Definir el Escenario ( Recordemos que es el controlador de la animación, es decir una función que actualice los valores del objeto, borre el canvas y repinte).
  • Llamar a iniciar la animación.

Bien, siguiendo los pasos vamos a importar la clase:

1
<script src="animation.js"></script>

Definimos los valores iniciales de nuestro reloj:

1
2
3
4
5
6
window.onload = function(){
  var anim = new Animation("reloj");
  var canvas = anim.getCanvas();
  var context = anim.getContext();
  var clockRadius = 90;  // El tamaño del reloj
};

 

Ahora vamos a definir el Escenario ( el stage) , aquí decidimos que vamos a pintar y como, esto incluye:

  • Determinar la hora.
  • Limpiar nuestro canvas.
  • Dibujar el nuevo reloj con la hora actualizada.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  anim.setStage(function(){
    // determinamos la hora
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    hours = hours > 12 ? hours - 12 : hours;
    var hour = hours + minutes / 60;
    var minute = minutes + seconds / 60;
   
    // limpiamos
    this.clear();
    // dibujamos
    var context = anim.getContext();
    context.save();
    context.translate(canvas.width / 2, canvas.height / 2);

    // el reloj en si
    context.beginPath();
    context.arc(0, 0, clockRadius, 0, Math.PI * 2, true);
    var grd = context.createLinearGradient(-clockRadius, -clockRadius, clockRadius, clockRadius);
    grd.addColorStop(0, "#F8FCFF"); // light blue
    grd.addColorStop(1, "#A1CCEE"); // dark blue
    context.fillStyle = grd;
    context.fill();

    // los numeros
    context.font = "18pt Times";
    context.fillStyle = "#024F8C";
    context.textAlign = "center";
    context.textBaseline = "middle";
    for (var n = 1; n <= 12; n++) {
      var theta = (n - 3) * (Math.PI * 2) / 12;
      var x = clockRadius * 0.8 * Math.cos(theta);
      var y = clockRadius * 0.8 * Math.sin(theta);
      context.fillText(n, x, y);
    }
    context.save();

    // Sombra
    context.shadowColor = "#bbbbbb";
    context.shadowBlur = 5;
    context.shadowOffsetX = 1;
    context.shadowOffsetY = 1;

    // bordes del reloj
    context.lineWidth = 3;
    context.strokeStyle = "#005EA8";
    context.stroke();
    context.restore();
   
    // el horario
    context.save();
    var theta = (hour - 3) * 2 * Math.PI / 12;
    context.rotate(theta);
    context.beginPath();
    context.moveTo(-10, -4);
    context.lineTo(-10, 4);
    context.lineTo(clockRadius * 0.6, 1);
    context.lineTo(clockRadius * 0.6, -1);
    context.fill();
    context.restore();
   
    // minutero
    context.save();
    var theta = (minute - 15) * 2 * Math.PI / 60;

    context.rotate(theta);
    context.beginPath();
    context.moveTo(-10, -3);
    context.lineTo(-10, 3);
    context.lineTo(clockRadius * 0.9, 1);
    context.lineTo(clockRadius * 0.9, -1);
    context.fill();
    context.restore();
   
    // segundero
    context.save();
    var theta = (seconds - 15) * 2 * Math.PI / 60;
    context.rotate(theta);
    context.beginPath();
    context.moveTo(-10, -2);
    context.lineTo(-10, 2);
    context.lineTo(clockRadius * 0.8, 1);
    context.lineTo(clockRadius * 0.8, -1);
    context.fillStyle = "red";
    context.fill();
    context.restore();
    context.restore();
  });

Por último iniciamos el ciclo de animación con el método start() para que se realice la animación del reloj en sí.

1
anim.start();

 

¡Pruebalo! 

 

Te Puede Interesar:

Trabajando con animaciones en HTML5
Dibujemos rectángulos con el mouse en HTML5
Como Implementar “Save Draft” y “Auto Save” en nuestras aplicaciones Web, II parte
 


Viewing all articles
Browse latest Browse all 18

Trending Articles