knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "  "
)
library(minisvg)

Introduction

There are at least 5 methods of animating SVG. These methods are detailed on the w3.org pages).

The 5 methods are as follows:

  1. SMIL - Synchronized Multimedia Integration Language. MDN doc
  2. CSS Animations w3 css animation reference
  3. CSS Transitions w3 css transitions reference
  4. SVG DOM manipulation via scripting w3 reference
  5. Web Animation w3 web animation reference

This vignette assumes you are familiar with SVG tags and document structures.

This document describes method 2 - CSS animation.

CSS animation - inline CSS

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Build a small SVG with a rectangle
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doc <- svg_doc(width = 240, height = 100)
doc$title("Attribute animation with SMIL")
doc$rect(x=0, y=0, width=240, height = 100, stroke='black', fill='white', stroke_width = 1)
doc$rect(id = 'myrect', x = 80, y=20, width=80, height=60)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Add a CSS style block to the SVG document. CSS definitions will override
# any inline definitions defined above
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doc$add_css(
"@keyframes moveit {
   from { fill: green; }
   50%  { fill: blue; }
   to   { fill: yellow; }
}")

doc$add_css(
"#myrect {
   fill: green;
   animation-name: moveit;
   animation-duration: 5s;
   animation-iteration-count: infinite;
}")

Show SVG text (click to open)

print(doc)


if (interactive()) {
  doc$show()
} else {
  doc
}

CSS animation - External CSS StyleSheet

This example uses animate.css which provided a nice range of useful CSS animations.

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Build a small SVG with a rectangle
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doc <- svg_doc(width = 240, height = 100)
doc$title("Attribute animation with SMIL")
doc$rect(x=0, y=0, width=240, height = 100, stroke='black', fill='white', stroke_width = 1)
doc$rect(x = 80, y=20, width=80, height=60)$
  update(class = "animated infinite bounce delay-2s")

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Add a reference to a CSS URL
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doc$add_css_url("https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css")

Show SVG text (click to open)

print(doc)


if (interactive()) {
  doc$show()
} else {
  doc
}


coolbutuseless/minisvg documentation built on May 2, 2020, 3:15 a.m.