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

Having trouble getting Angular ngIf to work in combination with Razor syntax?

I'm currently working with Angular Js and Razor. @{ var pageMode = (string) ViewBag.PageMode; } <div ng-if="@pageMode == 'answer'"> <h2>Greetings</h2> </div> Even though the value in ViewBag.PageMode is "ans ...

Tips to prevent elements from overlapping in Angular applications

I am facing an issue with my Angular-based app where I dynamically populate the page with table rows. There is an app-console element below the page that has a fixed position. Whenever I click the button to add a new row, it overlaps with the app-console. ...

Is there a way to access the scrolling element on the current webpage?

When the route changes, I need to locate the element with scrolling functionality on the new page and scroll it to the top using window.scrollTo(0,0). How can I achieve this? Here is my current code snippet: if (process.client) { router.afterEach((to, ...

Initiate a file download following the redirection of a user to a new page in NodeJS/Express

Overview I am currently developing a NodeJS project using Express. In the application, there are buttons visible to the public that trigger file downloads. These buttons are linked to protected routes which will redirect users to a login page if they are ...

What is the process for creating a custom Javascript function that can seamlessly integrate with other Javascript libraries?

Is there a way to create a method that can be linked or chained to jQuery methods and other library methods? For example, consider the following code snippet: var Calculator = function(start) { var that = this; this.add = function(x) { start = start ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

Setting up KCFinder integration in TinyMCE

I am utilizing TinyMCE as a text field, and I am in need of enabling image upload functionality within it. To achieve this, I am using KCFinder. However, I am encountering an issue where upon clicking on the 'Upload Images' button, only a white b ...

Please verify the utilization of jQuery.ajaxSettings.xhr

var _orgAjax = jQuery.ajaxSettings.xhr; jQuery.ajaxSettings.xhr = function () { var xhr = _orgAjax(); DoSomeLogging(); return xhr; }; I came across this code snippet and I'm trying to make sense of it. Does this mean that any $.ajax(...) ...

Unpredictable hovering actions when interacting with nested items within the hover layer

Imagine a scenario where we have the following elements: A container that holds everything A baseDiv inside that container // Let's create a base layer var container = document.getElementById('container') var baseDiv = document.createEl ...

How can I generate a fresh window/frame within my Javascript canvas?

Is there a way to open a new frame or window within the canvas using JavaScript? I am working on a game project where I want to implement a feature that displays additional information on a menu screen when a button is pressed. Currently, I have managed to ...

Uploading files with the help of Formik and the Material-UI stepper component

When attempting to upload a file, the entire component refreshes each time. The process involves 3 steps: the first step captures the user's name, the second step collects their address, and the third step allows them to upload a profile picture. Howe ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Navigate to a different page instead of the index page upon successfully signing in using Passport in MEAN.js

I'm currently developing a CRUD web application using MEAN.js. For Authentication, I have incorporated passport. After signing in, the app redirects to the index page. However, I am wondering how I can change the redirect to go to another page like ...

Guide on utilizing the <source> tag within v-img component in Vuetify.js?

When it comes to using webp images instead of jpg or png, some browsers may not support the webp format. In such cases, we can use the html tag < source > as demonstrated below, ensuring that at least a jpg image is displayed: <picture> < ...

Is it possible to set up multiple registries within a single package.json configuration?

Is it possible to define two different registries within the publishConfig section of the package.json file? The scenario is that we want to publish the artifact to two different locations depending on its purpose. For SNAPSHOT versions, we would like to ...

"Clicking on the hamburger menu causes the webpage to reset its scroll

I recently integrated a mobile hamburger menu into my website, which is primarily built around a single page. However, I noticed that whenever I open the menu, it automatically scrolls to the top of the page regardless of where you were previously scrollin ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...