Using a margin to refine an array of points in JavaScript

In my project, I am utilizing openCV.js for detecting contours in an image. Once the contours are identified, I proceed to implement certain filters and simplification techniques on these contours. Subsequently, I draw them as paths within an SVG for plotting purposes with a pen plotter. The issue I am currently facing lies in filtering out points from the generated array that fall between the boundaries of the SVG and the specified margin. While a clipping path could address this visually, it does not solve the underlying problem. What I require is for the actual paths to exclude these points so that they are not drawn by the pen plotter.

// Extract contour points and add to array
let points = [];
for (let j = 0; j < contours.size(); ++j) {
  const ci = contours.get(j);
  points[j] = [];
  for (let k = 0; k < ci.data32S.length; k += 2) {
    let p = [];
    p[0] = parseInt(ci.data32S[k]);
    p[1] = parseInt(ci.data32S[k + 1]);
    points[j].push(p);
  }
}
// Filter out contours with fewer than minNumPointsInContour 
let fPoints = points.filter(function (element) {
  return element.length >= minNumPointsInContour;
});
// Filter out points falling between margin and SVG edge (PROBLEMATIC AREA)
let mFPoints = fPoints.filter(
  (element) => element[0] >= marginSlider.value
);
// Simplify points before drawing
let sFPoints = [];
mFPoints.forEach((element) => {
  let simplifiedPoints = simplify(element, toleranceSlider.value, true);
  sFPoints.push(simplifiedPoints);
});

The critical section of concern is

let mFPoints = fPoints.filter((element) => element[0] >= marginSlider.value);
. Currently, this code snippet checks only the x-value of each element in the array against the margin value. However, I need to assess four conditions instead of one.

As the fPoints array is nested and contains point data, it is structured like [[0,0],[10,10],[10,20],etc]. At this stage, the output appears as follows:

My objective is to filter the fPoints array to include points where:

  • x-value (fPoints[0]) exceeds the margin
  • x-value (fPoints[0]) is less than SVG width - margin
  • y-value (fPoints[1]) surpasses the margin
  • y-value (fPoints[1]) is below SVG height - margin

I find the challenge of evaluating two different values within a nested array quite perplexing.

If more details are needed, you can review the full code here.

Answer №1

  // Removing points that are within the specified margin from the SVG edge
  // Assumes that outputSVG is an object of type SVG.js SVG.Svg
  
  let filteredPoints = fPoints.filter(
    (elem) => elem[0] >= marginSlider.value &&
               elem[0] <= outputSVG.viewbox().width - marginSlider.value &&
               elem[1] >= marginSlider.value &&
               elem[1] <= outputSVG.viewbox().height - marginSlider.value
  );

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

ReactJs not responding to rotation feature

System: Operating System: Windows 7 - 64 bit I am attempting to manipulate the rotation of a div in Reactjs by using click and drag mouse events similar to this example written in javascript code, which works flawlessly. I created a ReactJs applicatio ...

Retrieving data from a radgrid with the power of jQuery

Trying to extract the text from the label GetName in a radgrid using jQuery. Need to iterate through each record to check the value of the label. Can anyone provide assistance? Thanks! Below is the code for my radgrid. <telerik:RadGrid ID="Gridview1 ...

Synchronous: Establishing a connection to MongoDB once the server has successfully launched

I am curious to understand the interaction between Node.js asynchronous functions and MongoDB. If the server initializes before establishing a connection, and if my templates or Ajax requests rely on database data, will the serving of the HTML fail or will ...

Transferring data to server using AngularJS and Java Servlet Technology

I am currently facing a challenge in developing a webpage that enables file uploads from a local machine to a server using AngularJS and Java Servlet. My approach involves sending data to the server using $http.post and attempting to read the file data usi ...

Generating an Array Programmatically with Specified Type, Length, and Dimensions

I am currently faced with the task of parsing an IDX file, which is used to store multi-dimensional data of various types. After successfully decoding the header information, such as data type (Unsigned Byte, Signed Byte, Short, Int, Float or Double), numb ...

Disable default behavior in a SharePoint 2010 List new form with jQuery if conditions are not met

In the SharePoint 2010 List new form, there are 10 checkboxes available. I specifically need to choose exactly 3 of them and not less than that. Even though I implemented jquery for this purpose, it seems that the form does not stop submitting when the con ...

Unusual compilation issue encountered in Vue when trying to use a template for a slot

I encountered a strange issue where my Vue compiler was refusing to render the default named slot of a child component. Error: Codegen node is missing for element/if/for node. Apply appropriate transforms first. Even my VSCode highlighted this problem a ...

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

Issue observed: React Map layer is not loading until mouseEnter event happens

The map is displayed with the color fill only when a mouse enter event occurs. How can I make it trigger on load instead? I am working with react-simple-maps, and the JSON data is successfully loading the map on mouse enter. You can find the source code ...

Angular examine phrases barring the inclusion of statuses within parentheses

I require some assistance. Essentially, there is a master list (arrList) and a selected list (selectedArr). I am comparing the 'id' and 'name' from the master list to those in the selected list, and then checking if they match to determ ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Attempting to hide anchor tags for "register" and "login" while making the anchor tag for "logout" visible after signing in

After signing in, I want the register and login anchor tags to disappear and the logout anchor tag to appear. However, the login and register links stay visible on the page even after I sign in. <div class="navbar-nav ms-auto"> <% ...

Is it possible to execute node.js code within a Java script environment?

I have a javascript code that functions as a discord bot. Typically, to run this bot, I would open the command prompt in the js path and enter node {file_name}.js. Now, let's say I have another javascript code that I want to execute on button click an ...

I'm having trouble with my Rock Paper Scissors script. The console is showing an error message: "Uncaught SyntaxError: Identifier 'playerSelection' has already been declared."

Currently delving into the world of JavaScript, I've embarked on a project to create a console-based Rock Paper Scissors game. Here's the code snippet that I've come up with: <!DOCTYPE html> <html> <body> <script> ...

Dynamically defined type literals in Typescript

Recently, I came across an intriguing problem. I am attempting to develop a Vue.js wizard component that takes in configuration objects. The type of demo I have looks like this: type WizardConfiguration = { steps: Array<{ name: string, fie ...

Implementing new records in Laravel's result collection

I am currently working on a function to retrieve all maximum offers from the maxoffers table: public function maxoffers($id) { $offers = Maxoffer::where('article_id', $id)->latest()->get(['id', 'price', 'st ...

Resetting form after submitting an image in Meteor

In my Meteor App, I am using CFS for uploading files and everything is working fine except for one issue. When I try to upload another image, the previous uploaded image remains in the form, so I need a way to clear the form after submitting the new image. ...

Issue with manipulating currency conversion data

Currently, I am embarking on a project to develop a currency conversion application resembling the one found on Google's platform. The main hurdle I am facing lies in restructuring the data obtained from fixer.io to achieve a similar conversion method ...

C arrays used for capturing user input

Apologies in advance if this question has already been asked or seems trivial, as I am new to the C language and do not log in frequently. I am currently struggling with strings in C while learning the language. I know that char arrays are used instead of ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...