Save your AngularJS SVG file as a JPG

I am attempting to develop a custom directive that will allow me to convert an SVG file into a JPG or PNG format. I stumbled upon this website:

http://bl.ocks.org/mbostock/6466603

So, I decided to try and implement something similar with the following code snippet:

.directive('export', function () {
    return {
        restrict: 'A',
        scope: {
            target: '@export'
        },
        link: function (scope, element) {

            // Attach the click event listener to our button
            element.bind('click', function (e) {

                // Prevent the default action
                e.preventDefault();

                var target = document.getElementById(scope.target),
                    canvas = document.querySelector('canvas'),
                    context = canvas.getContext('2d');

                console.log(target);

                if (target) {

                    var preview = target.getElementsByTagName('svg');

                    console.log(preview);

                    var img = new Image;

                    img.src = preview[0];
                    img.onload = function () {

                        console.log('loaded');

                    };
                }
            });
        }
    };
});

The issue lies with the img.src. I'm uncertain if I am setting it correctly as the example on the aforementioned site uses a location instead of the actual svg file. Could someone provide guidance on how I can make this work?

Answer №1

By utilizing the SVG element, it is possible to generate a URL using the createObjectURL method. To gain more insights into this approach, check out the wider discussion on Rendering DOM elements onto a canvas on MDN.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = document.getElementById('container').innerHTML;
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);

img.onload = function () {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
}

img.src = url;
canvas {
  border: 1px dashed red;
}
<div id="container">
  <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" id="svg">
    <rect width="50" height="50"></rect>
  </svg>
</div>

<canvas width="200" height="200" id="canvas"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Facing issues with ReactCSSTransitionGroup as transitionAppear feature is not functioning

I'm having trouble with the appearance and disappearance of notifications. The transitionAppear property doesn't seem to be working as expected. I'm adding the notification popup item to the onBlur event. The animation for the leave event wo ...

Exploring the process of extracting data from a JSON response using AngularJS

Greetings to everyone, I am currently facing an issue in my controller. I am sending an HTTP POST request to the server and running a PHP file on the server side to check if the user is registered in my database. Below is the code snippet: $scope.sendPos ...

Open a fresh window using Javascript and add new content inside

After creating a script that opens a window and writes content when the button is clicked once, I noticed that clicking the button again causes the window to gain focus instead of rewriting the content. Does anyone have any ideas on how to fix this issue ...

Clear the Chrome Console of two warnings by resolving them in AngularJS

I'm getting ready to send out a Release Candidate of my Angular Application, but I'm having trouble resolving two warnings that keep popping up in the Chrome console. Here are the warnings: 'Attr.textContent' is deprecated. Please use ...

Utilizing the "each" function in jQuery to create click events for buttons that are linked to specific paragraphs

Right now, I am facing a situation where I have three buttons, each assigned with an ID that matches their order. Upon clicking a button, the paragraph associated with that order should hide itself using .hide(). My challenge lies in finding out how to ut ...

The jquery fancybox ajax modal popup fails to display in Internet Explorer 7

Recently, I utilized JQuery fancy box for the first time to display a menu list. When clicking on a specific item, the page is rendered properly in an iframe. However, if there is already an AJAX model popup present on the rendered page, it doesn't di ...

When utilizing Google Analytics in conjunction with Next.Js, encountering the error message "window.gtag is not

Encountering an error on page load with the message: window.gtag is not a function Using Next.js version 14.0.4. All existing solutions seem to hinder data collection, preventing the website from setting cookie consent correctly. I am uncertain about the ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Maximizing performance: optimizing Javascript usage in .net Web Application

After completing a web application using C#, ASP, and some javascript, my main page is cluttered with a mix of javascript/jQuery at the bottom. I have several ajax calls to web methods in this mess. Is there a way to organize this javascript into multipl ...

Javascript textfield button function malfunctioning

Here is the code I have created: HTML: <form method="post" id="myemailform" name="myemailform" action="form-to-email.php"> <div id="form_container"> <label class="descriptio ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code? <div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div> <div class="wrapp ...

What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting ...

Eliminating blank attributes within an array of objects

I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they ...

Is the navigation component's loss of properties due to a React router error?

After implementing react router for the first time, I noticed that the props passed to my nav component get lost once a new route is rendered. It's like the items in the cart are disappearing when I click checkout, but reappear correctly when I go bac ...

What is the best approach for making a drawer resizable?

I am interested in making the material ui drawer resizable width using a draggable handle. Currently, I have implemented a solution that involves adding a mouse event listener to the entire application and updating the width based on the position of the ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

When using the combination of Cucumber/Capybara with Angular, the test successfully passes with the Selenium driver but does not work with

I've been attempting to conduct feature tests on an Angular application, but I'm experiencing failures when using the poltergeist driver. It appears that the issue stems from the data-binding syntax being interpreted literally. For example, in th ...

An issue has arisen in Spring MVC where jquery-i18n-properties is unable to load the messages properties

Struggling with developing a Spring MVC 4 application using AngularJs and facing an issue with internationalization support. Attempting to utilize jquery.i18n-properties but encountering difficulty in loading messages_%s.properties. The error message rece ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...