0

this is my first time here. I load a SVG with Javascript into an HTML document. I need to replace the color of this SVG (it's a black image with transparency), which is placed into a canvas; however, when I put the css (style), nothing happens.

This is my code:

<!DOCTYPE html>
<html>
<head>
<title>TEST CANVAS</title>
    <script>

        function draw_img(){
            var img = document.getElementById("test");
            test.width = 300;
            test.height = 300;

            var ctx = test.getContext('2d');
            var source = new Image();
            source.src = './field/image.svg';
            source.onload = function(){
                ctx.drawImage(source, 0, 0);
            }                       
        }

    </script>
</head>
<style>
    canvas#test {
    fill:darkred;
}
</style>
    <body onload = "draw_img();">
    <h1>TEST</h1>

    <canvas id="test"></canvas>
    </body>
</html>

What's wrong with it? Sorry for my bad English and thanks in advance

KPavezC
  • 305
  • 2
  • 5
  • 20

1 Answers1

2

Canvasses are bitmap images. You can't apply CSS styles to them and expect that to change their colour. Once the SVG is rendered into the Canvas, it's contents are fixed, and can't be changed (except by pixel manipulation).

If you want to manipulate the colours of your SVG, you should inline it.

<style>
    svg#test {
        fill:darkred;
    }
</style>
<body>
    <h1>TEST</h1>

    <svg id="test">
        <rect width="50" height="50"/>
    </svg>
</body>

Demo here

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
  • Thanks for your answer, it was very useful. Finally had to load the svg directly into the HTML (without Javascript) and then, change its properties with the following Javascript: `function mod_img(){ var color="#FABB99"; document.getElementById("test").style.fill=color; }` @pattyd I've tried and it didn't show results – KPavezC Oct 08 '14 at 18:22