A direct path connecting two locations

Using an HTML canvas, I have implemented a connect-the-dots application where users can draw lines between multiple points from 1 to N upon touchstart.

Currently, there is validation in place to ensure that users can only draw lines connecting dots from point 1 to point 2 (..n). However, the issue lies in the lack of validation for straight lines. I am seeking an algorithm to address this problem. Here is my initial thought process:

  1. To determine if a line is straight between two points (x1,y1) and (x2,y2), calculate all coordinates using the slope formula y = mx + b.
  2. During touchmove events, verify that the x,y coordinates correspond to one of the calculated points from the previous step before drawing the line.

I am open to suggestions for better approaches or alternative methods to achieve this desired functionality. Any input would be greatly appreciated!

Answer №1

Edit: My initial interpretation of the question was off, it appears.

When it comes to validating the path: I believe it would be more practical to have a function that determines if a point is valid rather than computing all values in advance. Something along these lines could work:

function createPointValidator(x1, y1, x2, y2) {
    var slope = (y2 - y1) / (x2 - x1);
    return function (x, y) {
        return (y - y1) == slope * (x - x1);
    }
}

With this function, you can then use it like so for two points:

var isValid = createPointValidator(x1, y1, x2, y2);
var x = getX(), y = getY();// Assuming getX and getY fetch the user's new point.
if (isValid(x, y)) {
    // Draw
}

This method also offers some flexibility—you can adjust the function to allow for less precision to cater to those who may not draw perfectly straight lines but are close enough.

Precision: In line with my earlier comment, you can tweak the function to make it less strict. A suggested modification can be made like this:

We currently use the formula (y - y1) == slope * (x - x1), which is equivalent to

(slope * (x - x1)) - (y - y1) == 0
. By altering the zero to a positive number, we can consider points "near" the valid line as follows:

Math.abs((slope * (x - x1)) - (y - y1)) <= n

In this scenario, changing the value of n adjusts how closely a point must align with the line to be considered valid.

I am confident that this adjustment functions as intended, aiding in accommodating users who may draw slightly askew lines. However, it would be wise for someone to review my calculations.

Answer №2

function createLineGraph(x1, y1, x2, y2, color) {

    var distance = Math.ceil(Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
    var lineAngle = Math.atan2(y2-y1, x2-x1)*180/Math.PI;
    var xShift = distance - Math.abs(x2-x1);
    var yShift = Math.abs(y1-y2)/2;

    var newDiv = document.createElement('div');
    newDiv.style.backgroundColor = color;
    newDiv.style.position = 'absolute';
    newDiv.style.left = (x1 - xShift/2) + 'px';
    newDiv.style.top = (Math.min(y1,y2) + yShift) + 'px';
    newDiv.style.width = distance+'px';
    newDiv.style.height = '3px';
    newDiv.style.WebkitTransform = 'rotate('+lineAngle+'deg)';
    newDiv.style.MozTransform = 'rotate('+lineAngle+'deg)';

}

// Written by Gina Smith

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

Cutting an in-memory Base64 PNG using ONLY JavaScript on the client side without relying on canvas

Scenario: Working with JavaScript in a SDK environment, either on node.js or a browser. Situation: I have a base64 string containing a PNG image encoded using base64 (extracted from selenium webdriver's takeScreenshot function). Inquiry: How can I c ...

Continue moving the division to the left

Below is the HTML structure that I am working with: <div class="container"> <div class="menu"></div> </div> Accompanied by jQuery: $(document).ready(function() { $(".container").click(function() { $(".menu").css("l ...

Changing Text to Number in JavaScript

Looking to convert the string value of 41,123 into an integer using JavaScript. I attempted parseInt(41,123, 10) and parseFloat methods but haven't received the desired result. The issue seems to be with ParseInt and parseFloat when encountering com ...

'Redux' has not been declared ... along with ReactRedux and ReactDOM

I am currently working on the React/Redux exercise provided by FreeCodeCamp.org. Upon completing the exercise, my goal is to take it a step further by deploying it locally and then hosting it on Github. So far, I have utilized npx create-react-app {appnam ...

An array of Promise<Employee> cannot be used as a parameter for an array of type Employee[]

I am currently facing an issue with loading my Collection of Employees from a Firestore Database and fetching a 'Workday' for each Employee, which is stored as a Document in a Subcollection named 'Employees'. Below is the code snippet I ...

A guide to implementing child level filtering of JSON data with Lodash

Here is a JSON dataset I am working with: [ { "campaignId": 111, "campaignCategory": "Diabetes", "result": [ { "campaignType": 1, "name": "tes1" }, { "campaignType": 1, "name": "test22" ...

Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this: .directive('ngImageOnLoad', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { ...

The JavaScript function is not returning the correct string when implemented in an HTML

I have written a function in a JavaScript file to return a string, and I am calling this function within a script tag inside an HTML file. function getExp() { var exp = "]]><!\\[CDATA\\["; return exp; } However, when I c ...

Embed Text inside an HTML Canvas

As someone who is relatively new to working with html canvas, I am having a bit of trouble when it comes to containing text within the canvas area. Specifically, I am pulling text from a textarea and displaying it on the canvas, but it seems to stay as one ...

A versatile multi-select jQuery widget featuring the ability to choose options within a specific opt

I am on the hunt for a cool jQuery tool that has the following characteristics: It enables you to create multiple groups, such as: Group 1 - Sub 1 1 - Sub 1 2 - Sub 1 3 Group 2 - Sub 2 1 Group 3 - Sub 3 1 - Sub 3 2 By clicking on Group 1, for instance, ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

Feeling puzzled by the code snippet for vuejs-templates using webpack-simple?

Just starting out with javascript. Learning Vue.js through example reading. But feeling confused by the code snippet from vuejs-templates/webpack-simple. Specifically line 25 data () { return { msg: 'Welcome to Your Vue.js App' ...

Tips for bringing in pictures from outside directories in react

I am new to React and trying to import an image from a location outside of the project's root folder. I understand that I can store images in the public folder and easily import them, but I specifically want to import them from directories outside of ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

The hidden DIV containing an ASP.NET CheckBox consistently yields a value of false

I have a group of form elements located within a hidden div which looks like this: <div id="jDivUpdateFolder" style="display:none;"> <asp:TextBox ID="txtEditFolderName" runat="server"></asp:TextBox><br /> <asp:TextBox ID ...

Utilizing Node.js to iterate through arrays grouped by categories

Here is some data I need to work with [ [ '@test','1.2.6-unstable' ], [ '@test','1.3.2-unstable' ], [ '@test','1.4.6-unstable' ], [ '@test2','4.0.1-unstable' ], [ &ap ...

Unexpected format of _id is returned by Mongolian DeadBeef .toArray() method

My love for Mongolian deadbeef is strong, but I'm facing a challenge. I want the output of a simple .find() method to match the JSON format from Mongo's command line: $ db.mycollection.find(); # outputs.. # { ...some data... , "_id" : ObjectId(" ...

Limiting the input of a user to a maximum of a five-digit integer with a maximum of two decimal points using Angular 2 and ngModel

Currently, I am working on an input text field that utilizes [(ngModel)]. My goal is to restrict users to entering only a maximum of 5 digits with up to 2 decimal places. I believe creating a directive is the best approach to achieve this, however, I am un ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

Having trouble using a setTimeout() callback to display a Bootstrap Vue modal programmatically

I am currently working on a Vue CLI application (using the Webpack template) that utilizes Bootstrap Vue for displaying modal windows. In my Vue component's mounted() hook, I am attempting to programmatically show the modal by referencing the Bootstra ...