Obtaining file image input in TypeScript

I am struggling to integrate a file uploaded via the input type "file" into my Fabric JS canvas.

The steps of the process are as follows:

  • User initiates action by pressing a button (calls onAddImage)
  • User selects an image to upload
  • Selected image is added to the canvas using Fabric JS

This is the TypeScript code I have implemented so far:

const onAddImage = () => {
    document.getElementById("image-file")?.click(); //Trigger image file upload
    const fileInput = document.getElementById( // Retrieve file input 
      "image-file"
    ) as HTMLInputElement | null;
    


    // Use file?.files?.[0] here in an attempt to access the image



    if (fileInput) {
      fabric.Image.fromURL(<local image PATH supposed to be HERE>, function (img) { // Image path should be inserted here
        editor?.canvas.add(img);
      });
    }};

How can I pass the image from the input type file to the function as a string, especially when the image does not exist in the local directory? Do I need to cache the image somehow? Additionally, FabricJS offers two other functions (fromObject and fromElement) that may be relevant, but I'm unsure if they are necessary in this case.

Answer №1

<b> Insert Image from Local PC: </b>
    <input id="fileInput" type="file" accept="image/*" onchange="Upload()" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"> </script>
    <canvas id="canvas" width="1024px" height="576px" style="border:1px solid red"> </canvas>

    <script>
        var canvas = new fabric.Canvas('canvas');
        function Upload() {
            var input = document.getElementById("fileInput");
            var file = input.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var imgObj = new Image();
                    imgObj.src = event.target.result;
                    imgObj.onload = function () {
                        canvas.add(new fabric.Image(imgObj))
                    };
                };
                reader.readAsDataURL(file);
            }
        }
    </script>

var canvas = new fabric.Canvas('canvas');
        function Upload() {
            var input = document.getElementById("fileInput");
            var file = input.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var imgObj = new Image();
                    imgObj.src = event.target.result;
                    imgObj.onload = function () {
                        canvas.add(new fabric.Image(imgObj))
                    };
                };
                reader.readAsDataURL(file);
            }
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
    <b> Insert Image from Local PC: </b>
    <input id="fileInput" type="file" accept="image/*" onchange="Upload()" />
    <canvas id="canvas" width="1024px" height="576px" style="border:1px solid red"> </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

What is the best way to target all elements sharing a common class?

Currently, I have a Boolean variable stored in a hidden input field. When the user is signed in, it's set to false; otherwise, it's set to true. I have download buttons that should link to a file for download. My goal is to hide these buttons an ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

What steps can be taken to resolve the error message "AttributeError: 'WebElement' object does not have the attribute 'find_element_class_name'?"

try: main = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "main")) ) articles = main.find_elements_by_tag_name("article") for article in articles: header = article.find_element_c ...

Calculate the number of elements shared between two arrays using JavaScript

I am working with two arrays of objects and I need to determine how many different types of cars we have. The first array contains the IDs of all the cars, while the second array contains information about the types of cars. Here is the data: var arr = ...

Plugin refresh after callback

I have a webpage that features a row of buttons at the top, followed by some content below. Whenever one of the buttons is clicked, the content is updated using UpdatePanels. Within this content, I am attempting to incorporate the royal slider plugin, wh ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

What is the best way to create an "ArraySimilar" class using TypeScript?

Can someone guide me on creating an ArrayLike class in TypeScript? Edit: Got the solution from @jcalz, it's working perfectly for me. class CustomArray<T> implements ArrayLike<T> { length: number [index: number]: T } ...

Having trouble getting past the "Starting metro bundler" step when using the 'expo start' or 'npm start' command?

Currently, I am using React Native Expo to develop a mobile application. The process I followed includes the following steps: expo init myapp cd myapp expo start Initially, everything was running smoothly after executing these three commands. However, as ...

Issue with modal not being able to close the embedded video iframe

I have created a demo of a video in my footer that uses external CSS files and works perfectly. However, when I added it to the project, everything works except for closing the video. After clicking the play button in the footer, a modal appears on the sc ...

Validating mixed types and generics within an array using Typescript's type checking

I am currently working with a setup that involves defining interfaces for animals and their noises, along with classes for specific animals like dogs and cats. I am also storing these animals in an array named pets. interface Animal<T> { name: stri ...

Determining the value of an element by examining the clicked element

My goal is to determine the remaining balance in my cart based on the selected item. Let's say I have 3 items in my cart, and I choose one that costs $100. Previously, I stated that I had a total of $300. In my HTML code, there are elements with IDs ...

The process of uploading images to a server by making an AJAX call to a PHP file

I have an input file and I want to upload the attached file to the server with a message saying "uploaded successfully" when I click on the upload button. However, I am getting a "file not sent" message. (The uploaded images need to be saved in the uploa ...

Choose the right Vue.js component for optimal performance

I have a primary element within which there is a secondary element with vue.js 2.0. The issue arises when the secondary element relies on methods from the primary element. Here's an illustration: Vue.component('primary-element', { tem ...

Rendering data from the server using backbone.js: A comprehensive guide

Initially, this is the response received from the server $response = array(); $i = 0; while($result = mysql_fetch_assoc($query)){ $response[$i]["id"] = $result["ID"]; $response[$i]["post_ ...

When utilizing the data-target attribute, the Bootstrap dropdown becomes toggled

My Bootstrap dropdown is giving me trouble when I use it with data target. Removing data-target from the button makes it work, but then my website's dropdown only opens on the second click. So I tried using data-target to fix it, but now it won' ...

What steps do I need to take in order to make this array equation function properly?

I've developed a Javascript code that calculates the total linear footage based on values entered by the user. Below is the snippet of the JavaScript code... var totalLinealFootage = 0; for (var i = 0; i <= 24; ++i) { ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...

Unable to capture the text within the span element. Attempting to retrieve a response from a previously run javascript function

Currently, I am facing a challenging task in FileMaker using Webdirect. I have implemented a QR code generator and reader, and while I can successfully read the code, I am struggling to capture the result of the scan. The scanned data is displayed in a hid ...