Cambiar el color de fondo de SVG – Ejemplos de C#

El color de fondo de SVG es fundamental para proporcionar claridad y contraste visual, mejorando la visibilidad y la estética del contenido. Es vital para mantener la coherencia del diseño, mejorar la accesibilidad al proporcionar texto legible y definir límites en composiciones de varias capas. Puede cambiar el color de fondo de un SVG modificando el SVG directamente o aplicando estilos usando CSS o JavaScript.

Aspose.SVG for .NET API le permite editar un documento SVG y realizar cambios en su contenido.

En este artículo, aprenderá cómo aplicar color de fondo a archivos SVG usando Aspose.SVG for .NET y cómo trabajar con color de fondo para imágenes SVG dentro de documentos HTML usando la biblioteca Aspose.HTML C#.

Modificar SVG directamente

Para establecer el color de fondo de una imagen SVG, debe insertar un nuevo elemento SVG, como un rectángulo o un círculo, como primer elemento secundario en el documento SVG. Este método toma una regla sobre el orden de los elementos SVG: los elementos que aparecen más adelante en el código SVG aparecen encima de los que aparecen antes. Al colocar un rectángulo o un círculo al comienzo del SVG, crea efectivamente una capa de fondo que se ubica debajo de todos los demás elementos gráficos.

Agregar fondo a SVG

El método más común para configurar el color de fondo en SVG es crear un elemento <rect> que cubra todo el lienzo SVG. Este enfoque garantiza que el fondo sea parte del propio contenido SVG. El siguiente fragmento de código ilustra cómo agregar un fondo a SVG: cree un nuevo elemento rectangular en SVG que servirá como fondo. Para hacer esto, al rectángulo se le asignan los atributos width="100%", height="100%" y fill="#ebf3f6", y se coloca de manera que aparezca detrás de todo el resto del contenido SVG:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Set SVG Namespace Url
 6    string SvgNamespace = "http://www.w3.org/2000/svg";
 7
 8    string documentPath = Path.Combine(DataDir, "tree.svg");
 9
10    // Load an SVG document from the file
11    var document = new SVGDocument(documentPath);
12
13    // Get root <svg> element of the document
14    var svgElement = document.RootElement;
15
16    // Create a rectangle element and set the "width", "height" and "fill" attributes
17    var rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
18    rectElement.X.BaseVal.Value = 3;
19    rectElement.Y.BaseVal.Value = 3;
20    rectElement.SetAttribute("width", "100%");
21    rectElement.SetAttribute("height", "100%");
22    rectElement.SetAttribute("fill", "#ebf3f6");
23
24    // Add the rectangle element as the first child to <svg> element
25    svgElement.InsertBefore(rectElement, svgElement.FirstChild);
26
27    // Save the SVG document
28    document.Save(Path.Combine(OutputDir, "add-background-color.svg"));

Cambiar color de fondo SVG

Si su documento SVG tiene un elemento que sirve como fondo, como un rectángulo como en el ejemplo anterior, cambiar el color de fondo implica varios pasos:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Load an SVG document from a file
 6    var document = new SVGDocument(Path.Combine(DataDir, "add-background-color.svg"));
 7
 8    // Get root svg element of the document
 9    var svgElement = document.RootElement;
10
11    // Get the first <rect> element to change color
12    var rectElement = svgElement.QuerySelector("rect") as SVGRectElement;
13
14    // Set a new "fill" attribute value for the <rect> element
15    rectElement.SetAttribute("fill", "#fef4fd");
16
17    // Save the SVG document
18    document.Save(Path.Combine(OutputDir, "change-background-color.svg"));

Nota: Esta forma (método <rect>) es la más consistente en todos los navegadores y garantiza que el color de fondo sea parte del SVG, incluso cuando el SVG se exporta o se usa en diferentes contextos.

La siguiente figura muestra la imagen SVG original (a), la imagen con el fondo agregado (b) y la imagen en la que se cambió el color de fondo SVG (c):

Texto “Imagen svg original (a) e imagen svg con el color de fondo agregado (b) y cambiado (c)”

Cambiar el color de fondo usando CSS

Cambiar el color de fondo de SVG usando CSS es una tarea común que mejora la presentación visual de imágenes SVG dentro de las páginas web. Si bien los elementos SVG no admiten una propiedad nativa background-color, puedes lograr este efecto usando CSS para diseñar elementos SVG adicionales como <rect> o aplicando estilos a través de CSS externo, interno o en línea.

CSS en línea (Inline CSS): comprender los peligros

Puedes intentar intuitivamente usar la propiedad style="background-color" directamente en un elemento <svg>, esperando que funcione de la misma manera que lo hace para elementos HTML como <div> o <p> . Sin embargo, este enfoque está plagado de trampas y malentendidos. ¡Pero a veces funciona! En el siguiente ejemplo, usamos la propiedad background-color en el atributo style para el elemento <svg>:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Prepare a path to a source SVG file
 6    string documentPath = Path.Combine(DataDir, "tulips.svg");
 7
 8    // Load an SVG document from the file
 9    var document = new SVGDocument(documentPath);
10
11    // Get root <svg> element of the document
12    var svgElement = document.RootElement;
13
14    // Create a style attribute for <svg> element
15    svgElement.SetAttribute("style", "background: grey");
16
17    // Save the SVG document
18    document.Save(Path.Combine(OutputDir, "with-background-color.svg"));

¿Por qué parece funcionar?

En algunos navegadores o contextos de renderizado, puede parecer que funciona aplicar background-color a un elemento SVG, porque el navegador puede llenar el espacio asignado al SVG con el color especificado. Sin embargo, este efecto no se produce porque el SVG en sí tenga un fondo, sino porque el área alrededor o detrás del contenido SVG está coloreada. Es probable que se trate de un comportamiento accidental, más que de una característica definida por la especificación SVG.

El problema con este enfoque

El principal problema con el uso de background-color en el atributo style de SVG es que no forma parte de la especificación SVG. El estándar SVG no reconoce background-color como una propiedad de estilo válida para un elemento SVG. Esto significa:

  1. Lo que funciona en un navegador puede no funcionar en otro.
  2. El fondo en realidad no forma parte del contenido SVG, por lo que tiene menos control sobre su comportamiento y apariencia, especialmente cuando el SVG se exporta, imprime o procesa en otros contextos.

CSS interno – Internal CSS

CSS interno se refiere a estilos que están incrustados directamente en un documento HTML o SVG, generalmente en una etiqueta <style>. Esto le permite definir estilos específicos que se aplican sólo al documento actual, sin afectar a otros documentos ni requerir hojas de estilo externas.

En el siguiente ejemplo,

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Set SVG Namespace URL
 6    string SvgNamespace = "http://www.w3.org/2000/svg";
 7    
 8    // Load an SVG document from the file
 9    var document = new SVGDocument(Path.Combine(DataDir, "tulips.svg"));
10
11    // Get the root <svg> element of the document
12    var svgElement = document.RootElement;
13
14    // Create a <style> element
15    var styleElement = (SVGStyleElement)document.CreateElementNS(SvgNamespace, "style");
16
17    // Set the CSS content to define a background color class
18    styleElement.TextContent = @".background {fill: grey;}";
19
20    // Insert the <style> element at the beginning of the <svg> element
21    svgElement.InsertBefore(styleElement, svgElement.FirstChild);
22
23    // Create a rectangle element and set the class to "background"
24    var rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
25    rectElement.X.BaseVal.Value = 0;
26    rectElement.Y.BaseVal.Value = 0;
27    rectElement.SetAttribute("width", "100%");
28    rectElement.SetAttribute("height", "100%");
29    rectElement.SetAttribute("class", "background");
30
31    // Add the rectangle element as the first child to the <svg> element, after the <style> element
32    svgElement.InsertBefore(rectElement, svgElement.ChildNodes[1]);
33
34    // Save the SVG document
35    document.Save(Path.Combine(OutputDir, "add-background-color-with-css.svg"));

Este enfoque permite una separación clara entre estilo y estructura, aprovechando CSS para una gestión más sencilla y posibles cambios futuros en el color de fondo del SVG. El CSS interno es ampliamente compatible con todos los navegadores modernos, lo que garantiza una representación consistente de sus imágenes SVG.

La figura muestra la visualización del archivo SVG original (a) y el mismo archivo con el color de fondo agregado (b):

Texto “Imagen svg original e imagen svg con nuevo color de fondo”

Cambiar el color de fondo usando SVG Builder

En el siguiente código, SVG Builder agrega mediante programación un color de fondo a un documento SVG existente (para el archivo tulips.svg como en el caso anterior).

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Initialize an SVG document
 6    using (var document = new SVGDocument(Path.Combine(DataDir, "tulips.svg")))
 7    {
 8        var svg = new SVGSVGElementBuilder()
 9            .Width(100, LengthType.Percentage)
10            .Height(100, LengthType.Percentage)
11            .Build(document.FirstChild as SVGSVGElement);
12
13        // Create a new <g> element using SVGGElementBuilder and add <style> and <rect> elements to it
14        var g = new SVGGElementBuilder()
15            .Id("backgound")
16            .AddStyle(style => style
17                .Type("text/css")
18                .AddRule(".background", r => r.Fill(Color.AliceBlue))
19            )
20            .AddRect(rect => rect
21                .X(0).Y(0).Width(100, LengthType.Percentage).Height(100, LengthType.Percentage)
22                .Class("background")
23            ).BuildElement(document);
24        svg.InsertBefore(g, svg.FirstElementChild);
25
26        // Save the document
27        document.Save(Path.Combine(OutputDir, "add-background-color-with-builder.svg"));
28    }

El paso clave del código implica utilizar SVGGElementBuilder para definir un elemento de grupo (<g>) que incluye un elemento <style> con CSS interno. Este CSS define un color de fondo a través de la clase .background. Luego se agrega un elemento <rect> para aplicar el fondo utilizando esta clase. El grupo se inserta al comienzo del SVG, lo que establece efectivamente el color de fondo.

En el capítulo SVG Builder – Creación y modificación avanzada de SVG, encontrará una guía para manipular SVG de manera efectiva usando Aspose.SVG Builder API, que cubre aspectos desde la creación de elementos básicos hasta técnicas avanzadas como mixins y azúcar sintáctico.

Agregar color de fondo para imagen SVG dentro de HTML

Para continuar siguiendo este tutorial, debe instalar y configurar la biblioteca Aspose.HTML for .NET en su proyecto C#.

Cuando trabaje con documentos HTML que contienen imágenes SVG, es posible que necesite agregar un color de fondo a sus elementos SVG. Aunque los SVG suelen ser transparentes, agregar un fondo puede mejorar la visibilidad y la estética. El siguiente ejemplo de C# muestra cómo agregar mediante programación un color de fondo a todos los elementos SVG en un documento HTML usando C# y la biblioteca Aspose.HTML for .NET.

  1. Utilice uno de los constructores HTMLDocument() para cargar un archivo HTML.
  2. Emplee el método QuerySelector() para encontrar el elemento <style> dentro del documento HTML donde agregará una nueva regla CSS.
  3. Utilice la propiedad InnerHTML para generar el contenido actual del elemento <style> para garantizar que no se sobrescriban reglas importantes.
  4. Actualice la propiedad TextContent del elemento <style> para agregar una regla CSS para configurar el color de fondo de los elementos SVG.
  5. Utilice el método Save() para exportar el documento HTML actualizado a un archivo nuevo.

El archivo HTML fuente aspose-svg.html contiene CSS interno. Para agregar un color de fondo para todas las imágenes SVG, inspeccionaremos el contenido actual del elemento <style> y agregaremos una regla de estilo a los elementos SVG especificando el color de fondo que se aplicará a todas las imágenes SVG en el archivo HTML.

 1using System.IO;
 2using Aspose.Html;
 3...
 4
 5    // Prepare a path to a source HTML file with SVG image
 6    string documentPath = Path.Combine(DataDir, "aspose-svg.html");
 7
 8    // Load an HTML document from the file
 9    var document = new HTMLDocument(documentPath);
10
11    // Find a <style> element and assign a background color value for all svg elements
12    var styleElement = document.QuerySelector("style");
13
14    // Print content of the <style>
15    Console.WriteLine(styleElement.InnerHTML);
16
17    // Assign a text content for the style element
18    styleElement.TextContent = styleElement.InnerHTML + "svg {background-color: #fef4fd;}";
19
20    // Save the HTML document
21    document.Save(Path.Combine(OutputDir, "with-background-color.html"));

La figura muestra la visualización del archivo HTML original y el mismo archivo con el color de fondo agregado para la imagen SVG:

Texto “Página HTML original y el mismo archivo con el color de fondo agregado para la imagen SVG”

Cambiar el color de fondo usando JavaScript

Documento SVG

Para agregar dinámicamente un color de fondo a un archivo SVG usando JavaScript, puede incrustar un elemento <script> directamente en el SVG. Aquí hay una guía paso a paso sobre cómo lograr esto:

  1. Utilice la clase SVGDocument para cargar un archivo SVG.
  2. Acceda al elemento raíz <svg> del documento cargado. Este es el elemento al que agregarás el fondo.
  3. Utilice el método CreateElementNS() para crear un nuevo elemento <script>. Este script contendrá código JavaScript para agregar un color de fondo SVG.
  4. Defina el código JavaScript. Seleccione el elemento SVG, cree un <rect> con dimensiones completas y color de fondo, e insértelo como el primer elemento secundario para establecer el fondo.
  5. Agregue el elemento <script> recién creado al documento SVG.
  6. Guarde el documento SVG actualizado con el código JavaScript incrustado, que ahora incluye la lógica del color de fondo.
 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Prepare the path to the SVG document
 6    string documentPath = Path.Combine(DataDir, "tree.svg");
 7
 8    // Load the SVG document from the file
 9    var document = new SVGDocument(documentPath);
10
11    // Get the root <svg> element of the document
12    var svgElement = document.RootElement;
13
14    // Create a new <script> element
15    var scriptElement = document.CreateElementNS("http://www.w3.org/2000/svg", "script");
16
17    // Define JavaScript code to add a <rect> element as the background
18    scriptElement.TextContent = @"
19        var svgElement = document.getElementsByTagName('svg')[0];
20        if (svgElement) {
21            var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
22            rectElement.setAttribute('x', '0');
23            rectElement.setAttribute('y', '0');
24            rectElement.setAttribute('width', '100%');
25            rectElement.setAttribute('height', '100%');
26            rectElement.setAttribute('fill', '#fef4fd');
27            svgElement.insertBefore(rectElement, svgElement.firstChild);
28        };
29    ";
30
31    // Append the <script> element to the SVG document
32    svgElement.AppendChild(scriptElement);
33
34    // Save the modified SVG document
35    document.Save(Path.Combine(OutputDir, "svg-background-color-using-script.svg"))

SVG dentro del documento HTML

Para continuar siguiendo este tutorial, debe instalar y configurar la biblioteca Aspose.HTML for .NET en su proyecto C#.

Para cambiar el color de fondo de una imagen SVG dentro de un documento HTML usando JavaScript con Aspose.HTML for .NET, puede incrustar JavaScript directamente dentro del código SVG y luego usar Aspose.HTML para ejecutar el script. A continuación se muestra cómo puede lograr esto:

  1. Cargue un documento HTML utilizando el constructor HTMLDocument().
  2. Utilice QuerySelector() para buscar el elemento SVG por su ID u otro atributo.
  3. Utilice el método CreateElement() para crear un nuevo elemento <script>. Establezca su TextContent en código JavaScript que modifique el color de fondo del SVG.
  4. Agregue el nuevo elemento <script> al cuerpo del documento usando el método AppendChild(), asegurándose de que se ejecute el código JavaScript.
  5. Incluya una verificación condicional para manejar los casos en los que no se encuentra el elemento SVG, generando un mensaje relevante si es necesario.
  6. Utilice el método Save() para exportar el documento HTML actualizado con el script incrustado a un archivo nuevo.
 1using Aspose.Html;
 2using System.IO;
 3...
 4
 5    // Prepare a path to a source HTML file with SVG image
 6    string documentPath = Path.Combine(DataDir, "aspose-svg.html");
 7
 8    // Load an HTML document from the file
 9    var document = new HTMLDocument(documentPath);
10
11    // Find the SVG element by its ID (or any other attribute)
12    var svgElement = document.QuerySelector("svg[id='mySvg']");
13
14    if (svgElement != null)
15    {
16        // Create a new <script> element
17        var scriptElement = document.CreateElement("script");
18
19        // Define JavaScript code to add a <rect> element as the background
20        scriptElement.TextContent = @"
21            var svgElement = document.getElementById('mySvg');
22            if (svgElement) {
23                var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
24                rectElement.setAttribute('x', '0');
25                rectElement.setAttribute('y', '0');
26                rectElement.setAttribute('width', '100%');
27                rectElement.setAttribute('height', '100%');
28                rectElement.setAttribute('fill', '#fef4fd');
29                svgElement.insertBefore(rectElement, svgElement.firstChild);
30            };
31        ";
32
33        // Append the <script> element to the HTML document's body
34        document.Body.AppendChild(scriptElement);
35    }
36    else
37    {
38        // Handle the case where the svgElement was not found
39        Console.WriteLine("SVG element not found.");
40    }
41
42    // Save the SVG document
43    document.Save(Path.Combine(OutputDir, "svg-background-color-html-script.html"));

Conclusión

En este artículo, analizamos varios métodos para aplicar y cambiar el color de fondo de imágenes SVG utilizando las bibliotecas Aspose.SVG for .NET y Aspose.HTML for .NET:

En resumen, el método que elija debe depender del contexto en el que se utilizará el SVG y del nivel de control y coherencia requerido. Modificar el SVG directamente es generalmente el método más confiable, especialmente para archivos SVG independientes. Cuando se trabaja con SVG en documentos HTML, CSS y JavaScript brindan flexibilidad pero con posibles limitaciones.

Ver también

Texto “Color Converter”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.