Extract the canvas code line from a function without using the eval function

Greetings, fellow Stackers! Please pardon my formatting as this is my debut question on this platform.
I am currently working on a basic vector drawing tool. If you want to view the full CodePen code for reference, feel free to click here.

Here's the scenario: I've created a DRAW object with a 'temp' method that contains canvas drawing commands within a template structure. I aim to insert a variable code line from other methods of this object (such as add, sub...) in between.

temp(operation){

  ctx.beginPath();
  ctx.moveTo(o.x, o.y);  
  eval(operation);
  ctx.strokeStyle="red";
  ctx.stroke(); 
}

I'm seeking assistance in finding an alternative to using eval(), as it has been noted to be problematic and error-prone. Any other suggestions or recommendations would also be highly appreciated. Thank you kindly.

Answer №1

One way to utilize the temp function is by passing a function as an argument.

performTask(parameters) {
  // code implementation
}

temp(operation) {
  const parameters = {};

  operation(parameters);
}

temp(performTask)

Answer №2

After encountering an issue passing arguments to DRAW.temp along with an add function, I made a change that resolved the problem. Now, instead of passing arguments separately, I simply pass DRAW.add and specify the arguments (v1,v2) inside the temp method, which works correctly.

DRAW={
add(v1,v2){},
sub(v1,v2){},   /////operations

temp(operation){

  console.log(operation)
  ctx.beginPath();
  ctx.moveTo(o.x, o.y);  
  operation(v1,v2);/////////////input operation
  ctx.strokeStyle="red";
  ctx.stroke();
 } 
 };
var draw =DRAW.temp;
var add =DRAW.add;

draw(add)

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

Issues with HTML structure across various devices

Being a novice in web development, I've been experimenting with creating a modal body. The code snippet below represents my attempt at structuring the modal body: <div className="row modalRowMargin textStyle" > ... Your e ...

Preventing jQuery from loading a div if it already exists: a step-by-step guide

I've encountered an issue with a mock console on my website - every time the same input value is submitted more than once, jQuery reloads the div due to its specific id. Instead of cloning the div, I decided to append a message indicating that it alr ...

Retrieve dynamic data for Pivot in Devexpress AngularJS

I am currently working on an AngularJS web app where I am implementing a Pivot using devexpress, specifically utilizing the Field Chooser. You can find the example code here: In the provided example, static data is used. However, I need to fetch data dyna ...

Having trouble transferring ASP server control value to a Javascript function

Currently working with ASP.NET 2.0. My Entry Form contains various ASP.NET Server Controls, such as TextBoxes. I want to pass the value of a TextBox on the onBlur event. Here is an example of a TextBox code: <asp:TextBox ID="txtTotalTw" Width="80px" r ...

IE8 is not properly handling nested HTML elements that have the display:none property set

I am currently using jQuery to create a smooth fade-in effect for an <article> element that contains a <section> element. The outer element has CSS properties of display:none, position:fixed, and z-index:5. Meanwhile, the inner element is styl ...

What is the best way to programmatically change the event tied to an element's click

<div id="filters"></div> <div id="available"> <span class="badge badge-pill" onclick="addFilter()">Label</span> </div> function addFilter(event) { document.getElementById("filters").appendChild(eve ...

Creating an illustration with HTML5 from an image

Is it possible to draw on an image by placing a canvas on top of it? I am familiar with drawing on a canvas, but I am facing an issue where clicking on the image does not trigger the canvas for drawing. How can I resolve this? This is how my HTML looks: ...

Having trouble with Next.js environment variables not being recognized in an axios patch request

Struggling with passing environment variables in Axios patch request const axios = require("axios"); export const handleSubmit = async (formValue, uniquePageName) => { await axios .patch(process.env.INTERNAL_RETAILER_CONFIG_UPDATE, formVal ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

I am currently facing a challenge in animating my ng-show/ng-hide animation

This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...

The mouseup event fails to trigger upon dropping a component with React-dnd

Currently, I am working on a project that requires drag and drop functionality using the React-dnd package. While I have been able to successfully implement this feature, I am facing an issue with the target component where draggable items are supposed to ...

How to implement a modal popup in Vue.js using an anchor tag

As a newcomer to Vue.js, I'm facing an issue with creating a link in my navbar component that, when clicked, displays a modal component. I've noticed that the solutions I found are for buttons which use the data target attribute, but this isn&apo ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

What is the best way to handle a JSON arraylist in a Node.js environment?

Looking to extract and manipulate a specific data format in Node.js? Here is the data structure: {"orderSummary":[ { "name":"Wine", "ProductPrice":"500", "ProductQuantity":"2", "ProductCost":"1000", "SellerId":"2" },{ ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...