Drawing a modified SVG image in an HTML canvas in Firefox

I want to draw a modified SVG image on an HTML canvas.

It works great in Chromium, but not in Firefox. In Firefox, the image is pixelated.

Here is an SVG image:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="200" viewbox="0 0 200 200"> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/> </svg> 

And here is the code:

 <!DOCTYPE html> <html> <head> <title>Resized SVG in Canvas</title> <meta charset="utf-8"/> <script> window.addEventListener('load', function() { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), image = new Image(); image.src = 'circle1.svg'; image.height = 400; image.width = 400; image.addEventListener('load', function() { try { context.drawImage(image, 0, 0, 400, 400); } catch(error) { console.log(error); } }, false); }, false); </script> </head> <body> <canvas height="600" id="canvas" width="600"></canvas> </body> </html> 

Result:

enter image description here

I would like the SVG image to be resized without pixelation in Firefox, like in Chromium.

Currently, I put <img/> on top of the canvas to get an SVG image without pixelation, but it's pretty slow because there are a lot of images.

+4
source share
1 answer

I finally found a way to draw resized SVG on canvas in Firefox. The idea is to get the SVG source through AJAX and change the SVG using JavaScript with something like:

 var transformTag; transformTag = $(document.createElementNS('http://www.w3.org/2000/svg', 'g')) .attr('transform', 'scale(' + scaleX + ', ' + scaleY + ')'); svgElement.attr({ 'height': dh, 'viewbox': '0 0 ' + dw + ' ' + dh, 'width': dw }) .wrapInner(transformTag); 

Here is jsFiddle (without AJAX, but it's easy to change).

Since modifying and creating images is slow, I added a simple caching mechanism (not shown on the violin, but again, it’s easy to implement), and the speed is very fast.

It works in Chromium, Firefox and Opera (but for some reason the script does not work in Opera, although it works on my development server).

PS: If there is an jQuery alternative for document.createElementNS , I would like to know.

+3
source

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


All Articles