Can I make an animated SVG on Canvas?

I want to create an SVG animation, but I will make it Canvas. I know about CanVG, but I'm not sure that it does what I need. Display SVG elements animated using javascript inside a Canvas div, rather than a native SVG window. When I look at the sample CanVG code, it seems to point to the SVG file, and not to use the SVG code, which is part of the same file, and is manipulated in real time using javascript. Any help?

+4
source share
2 answers

I also ran into this problem some time ago and tried all the features mentioned above, unfortunately, to no avail. After some research, I found a way to introduce SVG into Canvas, with a little pain and extra work. So the solution is to define the elements of the SVG, then pass it to an array, and then render that SVG as an image.

Here is a short snippet of code:

SVG part:

var data = "data:image/svg+xml," + "<svg xmlns='http://www.w3.org/2000/svg' width='400' height='400'>" + "<foreignObject width='100%' height='100%'>" + "<div xmlns='http://www.w3.org/1999/xhtml' style='font: bold 160px Myriad Pro, Arial, Helvetica, Arial, sans-serif'>" + "<span style='color:rgb(32,124,202); opacity: 0.8; -webkit-text-stroke-color: white; -webkit-text-stroke-width: 2px'>" + letters[pos] + "</span>" + "</div>" + "</foreignObject>" + "</svg>"; characters.push(data); 

and js part:

 var letters = [...] // a pool of characters var images = new Array(letters.length); for (var i=0; i< letters.length; i++) { var textPosition = WIDTH/2 - (letters.length * CHAR_DISTANCE)/2; var txt = new Text(letters[i], textPosition + (i*CHAR_DISTANCE), HEIGHT/2, (Math.random() * 3) + 5 , (-Math.random() * 10) + 5); images[i] = new Image(); images[i].src = characters[i]; textArray.push(txt); } 

You can check all the source code here: https://esimov.com/experiments/javascript/404/

+3
source

There are several libraries (such as CanVG) that simply turn SVG into Canvas drawing commands. They will not help you with the animation.

For animation you have to do it yourself. You can try using CanVG to draw the SVG on the canvas, as it animates using a timer to update the canvas, but this is extremely messy and cannot be done if the browser does not support SVG (and if so, why do you want to do this ?)

If you want to manipulate SVG in real time, you will have to stick with SVG. Otherwise, you need to roll all your own state and interactivity onto the canvas. There are no shortcuts there [1], sorry.

[1] Well, there are several libraries for interacting canvas objects that allow you to use SVG objects as your objects, such as fabric.js. But depending on what you want, this may not be enough.

+2
source

Source: https://habr.com/ru/post/1433076/


All Articles