How can I swap out functions on the canvas without having to erase everything?

Is there a way to replace text with functions without clearing all drawn text on the canvas? Currently, I can only replace a function by clearing the entire canvas. I'm looking for a more dynamic approach where certain elements remain intact even after replacing functions.

Here is my current progress; take note of how the original text gets cleared:

 var $ = function(id) {
   return document.getElementById(id)
 };

 var canvas = this.__canvas = new fabric.Canvas('c');
 canvas.setHeight(300);
 canvas.setWidth(500);
  
 function changeTextOne() {
   canvas.clear();
   canvas.add(new fabric.IText('One', {
     left: 50,
     top: 100,
     fontFamily: 'arial',
     fill: '#333',
     fontSize: 50
   }));
 }
 
 // Original Text that should stay intact
canvas.add(new fabric.IText('This Should Stay The Same\nEdited Or Not', {
  left: 300,
  top: 45,
  fontFamily: 'Monsieur La Doulaise',
  fontSize: 27,
  hasBorders: false,
  hasControls: false,
  selectable: true,
  lockRotation: true,
  lockMovementX: true,
  lockMovementY: true,
  align: 'mid',
  originX: 'center',
  originY: 'center',
  centeredScaling: true,
}));


 function changeTextTwo() {
   canvas.clear();
   canvas.add(new fabric.IText('Two', {
     left: 200,
     top: 100,
     fontFamily: 'arial black',
     fill: '#333',
     fontSize: 50
   }));
 }

 
canvas {
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<button onclick="changeTextOne()">Change One</button>
<button onclick="changeTextTwo()">Change Two</button>
<canvas id="c"></canvas>

Thank you for your help!

Answer №1

To update text in a canvas using fabric.js, simply add an empty text element inside the canvas and then modify it within the appropriate functions. Don't forget to call canvas.renderAll after making the updates. It's worth mentioning that I am completely new to working with fabric.js.

var $ = function(id) {
   return document.getElementById(id)
 };

 var canvas = this.__canvas = new fabric.Canvas('c');
 canvas.setHeight(300);
 canvas.setWidth(500);
 
 var dynamicText = new fabric.IText('', {
   left: 50,
   top: 100,
   fontFamily: 'arial',
   fill: '#333',
   fontSize: 50
 })
 
 canvas.add(dynamicText);
 
 function textOne() {
   dynamicText.setText('ONE');
   canvas.renderAll();
 }
 
 // Text that should stay
canvas.add(new fabric.IText('This Should Stay The Same\nEdited Or Not', {
  left: 300,
  top: 45,
  fontFamily: 'Monsieur La Doulaise',
  fontSize: 27,
  hasBorders: false,
  hasControls: false,
  selectable: true,
  lockRotation: true,
  lockMovementX: true,
  lockMovementY: true,
  align: 'mid',
  originX: 'center',
  originY: 'center',
  centeredScaling: true,
}));

 function textTwo() {
   dynamicText.setText('TWO');
   canvas.renderAll();
 }
canvas {
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<button onclick="textOne()">One</button>
<button onclick="textTwo()">Two</button>
<canvas id="c"></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

Exploring the seamless integration of Material UI with React version 18

I am having an issue with my background not turning black in React version 18.2.0 when using makeStyles from Material UI version 4. Despite no errors in the code, the background remains unchanged. How can I fix this problem? import './App.css'; i ...

Here is a unique rewrite of the text: "Learn the process of toggling the tabindex for

Is there a way to dynamically change the tabindex of an element based on its visibility in the viewport? I am looking to either reset the current tabindex when entering a new section and assign new values to elements within that section, or disable and re- ...

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

What steps can be taken to ensure that any new elements generated by JavaScript do not disappear upon refreshing the page

I am currently working on a project where I am creating a list by collecting user information and storing it in a MySQL database. When the user clicks the 'add' button, a new element is added to the bottom of the existing list which is coded in H ...

Exploring MySQL: Retrieving Data Efficiently while Monitoring Server Performance

Currently, I am in the process of developing a web application that communicates with a MySQL database to send and receive data. My goal is to display any changes made in the database on the web page as quickly as possible. My main concern now is determin ...

Changing the color of individual buttons within a subset of buttons from a larger group of buttons

Is there a way to change the button colors individually when they are clicked? Requirements: The default color of the buttons should be grey. Upon first click, they should turn green. After the second click, they should become red. Finally, on the third ...

Personalize the material design datatable checkbox option

Recently, I delved into the world of material-ui design in conjunction with ReactJS. However, I have encountered a roadblock while attempting to customize the style of a checkbox that is being displayed under the <TableRow /> component. (Check out th ...

The background image does not appear to be displaying correctly on GitHub pages

I've encountered an issue where my svgs are not displaying as background-image or background on GitHub pages, even though they work fine locally. I utilized sass as a preprocessor for css, in case that detail is helpful. If anyone has insights on how ...

Suggestions on coloring polyline segments according to the density of neighboring segments surrounding the specific polyline segment

Apologies for the lengthy title, but I am interested in developing a polyline heatmap that changes color based on the number of lines within a certain proximity. Here is an example of what I have in mind: https://i.sstatic.net/W2lox.jpg Are there any inn ...

Is Next.js the Ultimate Serverless Rendering Tool with Cloudflare Workers?

I am currently using Next.js version 9 and I am interested in utilizing Next's serverless deployment feature by integrating my application with Cloudflare Workers. According to the documentation for Next.js, all serverless functions created by Next f ...

The webpack server is having trouble loading the CSS stylesheet

Currently, I am working on creating a webpage using ReactJS. I encountered an issue where the css stylesheet I created to modify some bootstrap classes (specifically for my Navbar fonts) was not being applied when linked in the html file. To troubleshoot ...

Issue with JQuery Ajax call within If condition

My Ajax call is working perfectly in one scenario, but not in another when placed inside an if statement. I'm relatively new to JS and Ajax, so I may be missing something fundamental. Any insights would be appreciated. Thank you. The function that wo ...

Get the unique _id value of the object once it has been added to an established collection

Recently, I encountered a mongodb document with the following schema: class: String, class_teacher: String, students: [ { student: String, marks: number } ] In this scenario, when adding a new student to the collection, each studen ...

Adjust the text placement on an adaptable image according to a particular section of the image

For accessibility reasons, I have an image that requires text to be overlaid on it. The image is responsive thanks to Bootstrap's img-responsive class. I need the text to stay positioned correctly on the image even as its size changes. Is there a way ...

Managing various types of form tags within a function-based view in Django

Coding Challenge: <form method="POST" enctype="multipart/form-data" id="p_formUpload"> {% csrf_token %} <fieldset class="form-group"> <p> { p_form|crispy }} </p> </fieldset> </form> ...

Send information to a Google form using AJAX requests

I have encountered an issue while attempting to send data via AJAX to a Google form. Despite receiving a success message with a statusCode of 0, the data does not show up in the form: var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"}; pos ...

Exploring the Integration of Node Modules with React

I am still learning about Node and I'm struggling to integrate an NPM package with my React project running on Node. Currently, I have a React component that successfully uploads a zip file through Node server scripts. Now, I am working on the next s ...

How to customize the background color in a Thymeleaf select element

Here is the HTML code I am working with: <select th:field="*{status.health}" th:value="${status.health}" th:class="health_color" th:name="status_healt ...

Adjust the text size to fit perfectly within the boundaries of a textarea input field

Is there a way to ensure that users type within a specific area with formatting and returns in a textarea element? I'm looking for a solution that limits overflow and ensures users stay within the designated area. How can this be achieved? I am worki ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...