Change the colour of an SVG and draw onto Canvas

I have a basic program that essentially just displays an imported svg. Is there any way I can change the fill of the svg?

var img;

function preload() { img = loadImage("assets/svgImage.svg") }

function setup() {

createCanvas(720, 400);

background(200);

fill(204, 101, 192, 127);

stroke(127, 63, 120);

image(img, 50, 50, 50, 50);

}

I tried something along the lines of:

function setup() {

img.drawingContext.fillStyle = '#475731' image(img, 50, 50, 50, 50)

}

But that doesn't seem to do anything for me.

I've tried implementing the p5-svg.js plugin, but I don't think it works for me. I have an enormous numbers of shapes that get rendered really nicely (and fast) in canvas, but screeches to a halt when the plugin translates all shapes to an SVG. Ideally, I'd like to be able to just draw an SVG (with my amended color) and then paint it onto the canvas. It seems like this plugin forces me to render the entire canvas as an SVG and I'm not sure that works for my use case.

Is there not anything built into p5 that does this?

The only other alternative I think of is loading the SVG as an element, and then using XHR as defined in this answer to potentially modify color:

var svg = document.getElementById('tmpSvg')

var blueCircle = (new XMLSerializer).serializeToString(svg);

var img = new Image();

img.src = "data:image/svg+xml;charset=utf-8," + blueCircle;

context.drawImage(img, 0, 0);

Edit: Sorry for the formatting... I'm new to the forum and haven't figured out the markdown formatting.

Tagged:

Answers

Sign In or Register to comment.