Captain Stack
Captain Stack

Reputation: 3844

How to animate DOM elements with JavaScript/CSS

I'm working on a chess game with some strategic visual overlays. One of them requires some light animation of pieces and squares, specifically, a slow and steady pulsing. My board is a with each being a single square. Pieces are shown by setting the background-image in CSS to an .svg of the piece it contains.

Can this be done in CSS? I'm using the latest browsers with no support for legacies, so I can use all the nifty CSS3 stuff. Another option I was thinking was to set the background-image of the board to an animated .gif of the piece pulsing. Would this work?

Are there any other ways to do this I haven't mentioned? I would like to avoid packages/frameworks, but I am using jQuery.

CLARIFICATION:

I want to make the chess piece kind of pulse (flash?) in place slowly for emphasis. I want it to be a slow, subtle, and consistent pulse that persists until another event turns it off.

Upvotes: 1

Views: 773

Answers (2)

Dagg Nabbit
Dagg Nabbit

Reputation: 76776

It sounds like you're looking for CSS animations.

Take a look here: http://www.w3.org/TR/css3-animations

In particular you'll need the following timing functions:

  • animation-name, to specify the set of keyframes to use.
  • animation-duration, to specify the speed of the animation.
  • animation-iteration-count, to repeat the animation.
  • animation-direction, to alternate the direction of the animation.

And you'll need to create some keyframes, which let you specify what CSS properties are modified by the animation.

Also, you'll need vendor prefixes on everything, so you need to write -webkit-animation-name rather than animation-name (for example), and repeat everything for -moz and other vendors.

Here's an example for webkit that creates a pulsating opacity effect. You can experiment with the properties in the from and to sections to animate size, color, etc.

.chess-piece {
    -webkit-animation-duration: 1s;
    -webkit-animation-name: pulse;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-direction: alternate;
}
@-webkit-keyframes pulse {
    from {
        opacity: 0.5;
    }
    to {
        opacity: 1;
    }
}

JSFiddle example for webkit and moz

Upvotes: 2

user1546328
user1546328

Reputation:

That is quite possible and easy to do. As I understand it, you want to make some kind of glowing animation of the active chess figure? Here's how I would go implementing a solution: Create 2 pngs, one with the chess figure in its unflashy ordinary state and one with its fully illuminated state. Then use jQuery to change the opacity of the illuminated state from 0 to 100 and back to 0 again.You can send the jQuery "on animation finish" signals to achieve this. You can than just use some kind of simplified observer pattern to cancel the effect once an event occurs.

Upvotes: 0

Related Questions