Opt for using SVG elements over raster images in the canvas

My goal is to develop an application similar to this using JavaScript and canvas elements.

To achieve this, I initially used KineticJS as the canvas library to create a draft. The teeth are represented by PNG images while the lines are drawn using KineticJS Line objects.

A friend recommended a different approach of drawing everything as one large SVG file where each tooth and line is defined as a separate path. This SVG would then be loaded onto the canvas with distinct IDs for manipulation purposes.

Although I explored the documentation for both fabric.js and KineticJS, I couldn't find a straightforward method to load and parse an entire SVG on the canvas for manipulation based on unique IDs.

Given my limited experience with SVG graphics, I'm unsure if my envisioned approach is feasible. Can this idea of loading a complete SVG composed of teeth and lines be realized?

Currently, I am loading individual teeth as images using KineticJS.

Periodontogram.prototype.initializeImageObjects = function (){
    var obj = this;
    if (this.DEBUG){
        console.log("initializing ImageObjects:")
    }
    var check = function (item){return item !== undefined;}
    var url = this.options.url; 
    var imageObj;
    var image;

    this.options.imageFilenames.forEach(function (filename, index){
        if (obj.DEBUG){
            console.log("Loading "+filename+" image");
        }
        var src = url+'/'+filename;
        imageObj = new Image();
        imageObj.src  = src;
        imageObj.onload = function (){
            if (obj.DEBUG){
                console.log("Image "+src+" successfully loaded");
            }
            image = new Kinetic.Image({
                x:0,
                y:0,
                id: filename.split('.')[0],
                width: this.width,
                height: this.height,
                image:this
            });
            obj.imageObjects[index] = this;
            obj.teethImages[index] = image;
            if (obj.imageObjects.filter(check).length === obj.options.imageFilenames.length )    {
                if (obj.DEBUG){
                    console.log("All Images loaded successfully");
                    console.log("ready to call rest methods")
                }
                obj.positionImages();
                obj.createLineGroups();
                obj.createLabelGroups()
                obj.createStage();
                obj.drawOnScreen();
                $("#"+obj.container).width(obj.stage.getWidth());
                $("#"+obj.container).height(obj.stage.getHeight ());
                obj.callback();
                $.event.trigger({
                    type:'finishLoading',
                    obj: obj
                });

            }

        };

    });

}

I aim to simplify this process by replacing it with the loading of a single SVG file containing both teeth and lines.

Answer №1

With FabricJS, you can easily transform an existing SVG URL/string into a Fabric.PathGroup by converting, decomposing and recomposing it. After that, using mySvgGroup.getObjects(), you can access the individual tooth paths and manipulate them according to your needs.

For more information, visit:

On the other hand, KineticJS allows you to input the path data of a single SVG tooth and display it on canvas.

Learn more here:

However, for greater flexibility, it is recommended to create individual SVG paths for each tooth and then import these separate SVGs into either KineticJS or FabricJS.

This way, you can personalize your manipulations by assigning unique IDs to each tooth:

  • Position the teeth using [x,y] coordinates,
  • Resize without losing quality,
  • Group the teeth and add annotations/drawings as needed,

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

Issue: { error: 'Unrecognized interaction', error code: 10062} in discord.js version 14

Every command runs perfectly fine except for /rank, which triggers the "Unknown interaction" error. This only happens when there are no issues with error handling, such as providing a valid user id and rank id. When there are problems, it works fine. I pr ...

Strange occurrences with Javascript events, removeEventListener failing to function

I am facing a challenge with removing event listeners in my code to prevent multiple calls to an event. I need the flexibility to call these functions multiple times without causing conflicts. Currently, my solution is not effectively removing the event l ...

When scrolling on an IOS mobile device, the .on(click) event is triggered for fixed position elements

Whenever I click on an li element or menu, a function is triggered that moves the nav container to the left by the width of the window. However, on my iPhone, after I click to slide the container off the screen, the event gets triggered repeatedly every ti ...

When using the map function in NodeJS, it may result in an empty array being

I attempted to get results from a mssql database using the mssql npm package and store them in an array. However, I'm facing an issue where the response seems to return an empty array outside of the map function. Any assistance on this matter would be ...

Modify input field background color

In my Angular project, I have an input field structured like this: <input class="form-control" type="text" ng-model="newBook.color"> Whenever the value in this input changes, I want to dynamically change the background color of a specific div. Wit ...

What is the maximum number of JSON responses that can be handled by AJAX?

Upon entering the site, I am attempting to receive a JSON as an AJAX response. However, I am curious if there is a limit to the size of the object I can retrieve - whether through a GET or POST request? $http({ method: 'POST', url: &apos ...

Having issues with adding a form group to a form array in Angular 2 Reactive Forms

I am currently working on a dynamic form and I am looking to add form groups dynamically. Below is the code snippet that I have been trying to get to work: import {Component, OnInit} from '@angular/core'; import {FormGroup, FormBuilder, FormArray ...

Interpreting JavaScript through code written in Ruby

Currently, I am working on a test code using Ruby where my objective is to parse an HTML source file of a website. The HTML source contains a JavaScript variable that I need to compare with other values. For instance: <script type="text/javascript" lan ...

Ensuring Radio Button Selection is Valid

Has anyone had success validating radio buttons using Javascript? I'm having some trouble and would appreciate any help. Here is the code I've been working with: <form action="submitAd.php" method="POST" enctype="multipart/form-data" name="pa ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

Press the button to switch between displaying one component and hiding another component within reactjs

I am working on a project with two distinct buttons: one for grid view and another for list view. <button onClick={() => setClassName('jsGridView')} title="Grid View" > <IoGrid className="active" s ...

The issue of data loss in a PDF file while using the FileReader

My current challenge involves the necessity of sending data to a server in JSON format exclusively, and I also need to include a PDF file along with other form data within the JSON. Initially, I attempted to convert the PDF into a base64 string following a ...

"Enhance your Django website with a dynamic voting button using AJAX

I am working on a project where I have implemented the following code: (r'^oyla/(\d+)/$', oyla), Here is the view associated with this code snippet: @login_required def oyla(request, id): if request.is_ajax(): entry = Entry.ob ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

Tips for retrieving specific data for display in an AngularJS application utilizing Node.js and MongoDB

Currently, I am in the process of developing a MEAN stack blog application. My main objective is to retrieve a specific "blog" from a list of blogs (displayed using ng-repeat) stored in my Mongo database via a Mongoose schema and then render it in a separa ...

Using the React Router <Link> component inside a conditional ternary statement

I am trying to incorporate a Ternary operator into React JSX, specifically for creating a conditional React Router Link tag like so: <Table.Cell>{`${user.company !== null ? <Link to={`/companies/${user.company._id}`}>`${user.company.name}`< ...

When the image transitions, the second dot does not activate

Recently, I developed a small automatic image slider that transitions to a new image every 4 seconds by utilizing the following code: setInterval(displayImage, 4000);. The image transitions are functioning correctly; however, there seems to be an issue w ...

When I combine useState with another function in onClick, it does not function properly

This is the state I have created: const [list, insert] = React.useState(["a","b"]); I want a button that, when pressed, will update list to be ["a","b","c"] The first method works perfectly: <button onClick={() => insert(list.concat(["c"]))}>I ...

Context Provider executing SetInterval twice

For some reason, the below code in global.js is running twice when I run my react app, but I can't figure out why. I have used setInterval to test, and the intervals are always running two times. Perhaps I am not initializing correctly. Even after rem ...

Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows use ...