jQuery addClass example

Change class name on click in jQuery

by eget teteete

HTML

<canvas id="canvas" width="400" height="400"></canvas>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#canvas {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function(x, y, radius, fillCircle) {
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2, false);
  if (fillCircle) {
    ctx.fill();
  } else {
    ctx.stroke();
  }
};
// Конструктор Ball
var Ball = function() {
  this.x = width / 2;
  this.y = height / 2;
  this.xSpeed = 5;
  this.ySpeed = 0;
};
// Обновляем позицию мяча соответственно его скорости
Ball.prototype.move = function() {
  this.x += this.xSpeed; // Диагональ
  this.y += this.ySpeed; //Вертикаль
  if (this.x < 0) {
    this.x = 0; //Левая грань
    this.xSpeed = 5;
  } else if (this.x > width) {
    this.x = width; //Правая грань
    this.xSpeed = -5;
    this.ySpeed = 5;
  } else if (this.y < 0) {
    this.y = height;
    this.ySpeed =5;
  } else if (this.y > height) {
    this.ySpeed = -5;
  }
};
// Рисуем мяч в его текущей позиции
Ball.prototype.draw = function() {
  circle(this.x, this.y, 10, true);
};
// Задаем направление движения по строке с названием действия
Ball.prototype.setDirection = function(direction) {
  if (direction === "up") {
    this.xSpeed = 0;
    this.ySpeed = -5;
  } else if (direction === "down") {
    this.xSpeed = 0;
    this.ySpeed = 5;
  } else if (direction === "left") {
    this.xSpeed = -5;
    this.ySpeed = 0;
  } else if (direction === "right") {
    this.xSpeed = 5;
    this.ySpeed = 0;
  } else if (direction === "stop") {
    this.xSpeed = 0;
    this.ySpeed = 0;
  }
};
// Создаем объект-мяч
var ball = new Ball();
// Объект для перевода кодов клавиш в названия действий
var keyActions = {
  32: "stop", // остановка
  37: "left", // влево
  38: "up", // вверх
  39: "right", // вправо
  40: "down" // вниз
};
// Обработчик события keydown, будет вызван при каждом нажатии
// клавиши
$("body").keydown(function(event) {
  var direction = keyActions[event.keyCode];
  ball.setDirection(direction);
});
// Функция...