Mastering SVG
eBook - ePub

Mastering SVG

Ace web animations, visualizations, and vector graphics with HTML, CSS, and JavaScript

Rob Larsen

Compartir libro
  1. 312 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Mastering SVG

Ace web animations, visualizations, and vector graphics with HTML, CSS, and JavaScript

Rob Larsen

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Take the plunge and develop cross-browser-compatible and responsive web designs with SVG

Key Features

  • Master the art of custom animations and visualizations with SVG, CSS, and JavaScript
  • Combine SVG with third-party libraries and frameworks such as React, JQuery, D3, and Snap.svg for GUI-rich apps
  • Create an awesome user experience with high-performance graphics for your web applications

Book Description

SVG is the most powerful image format in use on the web. In addition to producing resolution-independent images for today's multi-device world, SVG allows you to create animations and visualizations to add to your sites and applications. The simplicity of cross-platform markup, mixed with familiar modern web languages, such as CSS and JavaScript, creates a winning combination for designers and developers alike.

In this book, you will learn how to author an SVG document using common SVG features, such as elements and attributes, and serve SVG on the web using simple configuration tips for common web servers. You will also use SVG elements and images in HTML documents.

Further, you will use SVG images for a variety of common tasks, such as manipulating SVG elements, adding animations using CSS, mastering the basic JavaScript SVG (API) using Document Object Model (DOM) methods, and interfacing SVG with common libraries and frameworks, such as React, jQuery, and Angular.

You will then build an understanding of the Snap.svg and SVG.js APIs, along with the basics of D3, and take a look at how to implement interesting visualizations using the library. By the end of the book, you will have mastered creating animations with SVG.

What you will learn

  • Deliver the elements that make up an SVG image
  • Replace your old CSS sprites with SVG
  • Understand animation and data visualization with SVG are explained in pure JavaScript and using common libraries
  • Use SVG to scale images across multiple devices easily
  • Harness the power of CSS animations and transformations to manipulate your SVG images in a replicable, remixable way
  • Interface SVG with common libraries and frameworks, such as jQuery, React, and Angular

Who this book is for

This book is for web developers and designers looking to add animation to their projects. Some experience with HTML, CSS, and JavaScript is required.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Mastering SVG un PDF/ePUB en línea?
Sí, puedes acceder a Mastering SVG de Rob Larsen en formato PDF o ePUB, así como a otros libros populares de Informatique y Développement Web. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781788621984
Edición
1
Categoría
Informatique

Working with SVG and CSS

This chapter will focus on the intersection between SVG and CSS. While JavaScript is the most powerful tool for working with SVG, SVG without CSS wouldn't be nearly as popular as it has become. SVG, as you've learned, is well-suited for the modern web and is often the best answer to an RWD question. Because of that, it's been wholeheartedly embraced by designers and developers for producing images for the web.
This preference for SVG is a good one for the web as a whole and should be cultivated. This chapter will hopefully illustrate why.
In this chapter, we'll learn about the following:
  • Using CSS background images
  • How to optimize data URIs for SVG
  • SVG sprites versus icon fonts
  • How the different ways of embedding SVG interact with CSS
  • Using common CSS properties to manipulate SVG
  • Using SVG-specific CSS properties to manipulate SVG
  • Basic CSS animations and transitions with SVG

CSS background images

You've already seen examples of using CSS for background images all the way back in Chapter 1, Introducing Scalable Vector Graphics. This section will add some more details to using SVG in this way.
In this initial, basic example, we add an SVG image of a stylized letter R as the background image of a div. One important aspect is setting the background-size property. The natural size of the SVG image is 458 by 392. In this case it's set to be half that size in order to fit into the size of the div:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mastering SVG- CSS Background Images</title>
<style type="text/css">
.logo{
width: 229px;
height: 196px;
background: url(icon.svg);
background-repeat: no-repeat;
background-size: 229px 196px;
}
</style>
</head>
<body>
<div class="logo">
</div>
</body>
</html>
Rendered in the browser, we get the following:
Other than providing for high pixel density displays (which is a great feature), this doesn't get you much beyond what a PNG provides.
In an environment where relative units are being used, you can leverage SVG's ability to scale with contain or cover as the value of background-size to really take advantage of SVG. In the following example, the same previous logo is applied as a background image, alongside some text. All of the metrics are relative, using the root em (rem) unit. The background image is set with a background-size value of contain. contain ensures that the logo will be shown, in its entirety, constrained by the height and width of the containing element. Since we're using an SVG image as the background image, the base font for the document (and therefore the calculation of the root em) could scale from 16 pixels (the browser default) to 1,600 pixels and the SVG background would be able to scale to match:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mastering SVG- Relative Background Images </title>
<link href="https://fonts.googleapis.com/css?
family=Raleway:600" rel="stylesheet">
<style type="text/css">
.logo{
width: 14.3rem;
height: 14.3rem;
background: url(icon.svg);
background-repeat: no-repeat;
background-size: contain;
background-position-y: 2.5rem;
}
h1 {
font-family: Raleway, sans-serif;
font-size: 2rem;
}
</style>
</head>
<body>
<div class="logo">

<h1>Rob Larsen</h1>
</div>
</body>
</html>
Rendered in the browser, we get the following:
There's not much here that's new, but it's such an important use for SVG on the modern web it's worth taking some time to reinforce the pattern.

Data URLs for SVG background images

If you're performance-minded, you might be wondering about the technique of embedding a background image directly in your CSS via a data: URL. Data URLs allow you to embed files directly into a document via a special data: URL. This technique allows you to save an HTTP request.
When working with binary formats such as JPGs or PNGs, the image data needs to be base64-encoded. While this will work with SVG images, it's actually faster (https://css-tricks.com/probably-dont-base64-svg/) to embed the SVG images as an SVG source. This works because, in addition to base64-encoded data, you can directly embed text. SVG is, of course, a text format. You just need to do a couple of things to the SVG to make it work properly. You should read the full article by Taylor Hunt for the details (https://codepen.io/tigt/post/optimizing-svgs-in-data-uris) but the basic steps are:
  • Use single quotes for attribute values
  • URL-encode any non-safe characters (<, >, #, and so on)
  • Double quote the data URL
Converting the initial example, we get code that looks as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mastering SVG- CSS Background Images with Data
URLs</title>
<style type="text/css">
.logo{
width: 229px;
height: 196px;
background: url("data:image/svg+xml,%3Csvg
xmlns='http://www.w3.org/2000/svg' height='392' width='458'%3E%3Cg stroke='%23000' stroke-width='14.17'%3E%3Cpath d='M96.42 60.2s14 141.5-58 289l145.5-18.4 55.4-276.7z' fill='%23000012'/%3E%3Cpath d='M145.42 188l108.5 171.6 189.2 24.4-123.4-196z' fill='%23000012'/%3E%3Cpath d='M70.12 43.7s14 141.5-58 289l145.5-18.4 55.4-276.7z' fill='%23e9c21b'/%3E%3Cpath d='M59.02 23.6l116.2 237.2c-.1 0 411.3-239.1-116.2-237.2z' fill='%23000012'/%3E%3Cpath d='M119.12 171.6l108.5 171.6 189.2 24.4-123.4-196z' fill='%233fc4eb'/%3E%3Cpath d='M32.62 7.1l116.2 237.2S560.22 5.2 32.62 7.1z' fill='%2359ea39'/%3E%3C/g%3E%3C/svg%3E");
background-repeat: no-repeat;
background-size: 229px 196px;
}
</style>
</head>
<body>
<div class="logo">
</div>
</body>
</html>
While this is actually pretty straightforward to prep by hand (the example here was hand-coded), there are some tools available that can do this for you if you're looking to squeeze out all the bytes. There's a node module (https://www.npmjs.com/package/mini-svg-data-uri) and a SASS function (https://codepen.io/jakob-e/) that can help you build this capability into your workflow.

SVG sprites and icon sets

This section isn't strictly about CSS, but does discuss a replacement for a common CSS-driven solution for adding icons to applications so this seems such as the best place to discuss it.
If you're reading this book you're probably somewhat familiar with the idea of icon fonts such as GLYPHICONS (http://glyphicons.com/) or Font Awesome (https://fontawesome.com/icons?from=io). If you're not, they are fonts that, instead of representing characters that can be read as language (as in, the characters that you're reading right now), they present different images that can be used as icons for a site or application.
For example, you could create an interface for a video player using Font Awesome without having to design a single element.
The following code sample shows what that implementation might look suc...

Índice