JavaScript: Trouble with statement execution

My code is designed to classify a point as 1 if it's above the line y=x, and -1 if it's below the line y=x. I visually represent this line in a canvas by plotting y=x (although due to invertion on the y-axis, it appears like y=-x). For each point, I draw it using green color if it's 1 and red color if it's -1. The expected outcome is a straight line with one side being green and the other side being red. However, when running the code, the result turns out to be unexpected.

This is how I label my points using JavaScript:

function Point(x, y){
    this.x = x;
    this.y = y;
    this.label = 0;
    if(this.y >= this.x){
        this.label = 1;
        console.log(x, y, "UP");
    }else if(this.y < this.x){
        this.label = -1;
        console.log(x, y, "Down");
    }
}

And here is the code for painting the points in the canvas:

function draw(){
  ctx.clearRect(0, 0, can1.width, can1.height);
  ctx.strokeStyle = "yellow";
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(can1.width, can1.height);
  ctx.stroke();
  ctx.closePath();
  for(var i = 0; i < points.length; i++){
    var x = points[i].x;
    var y = points[i].y;
    if(points[i].label == 1){
        var color = "Chartreuse";
    }else{
        var color = "red";
    }
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, Math.PI * 2, false);
    ctx.fill();
    ctx.closePath();
  }
}

Upon running the code in the browser, the visual output appeared as shown in this image: https://i.sstatic.net/yHM2I.png

The visualization seems to only partially align with expectations. Any assistance or insights would be greatly appreciated!

Edit: Note that the x and y values are randomly assigned in other parts of the code.

Thank you for your help!

Answer โ„–1

Feel free to extend the yellow line to where x === y, instead of just restricting it to the edge of the canvas.

ctx.lineTo(Math.min(can1.width, can1.height), Math.min(can1.width, can1.height));

Answer โ„–2

Allow me to present the same concept in a different light.

ctx.lineTo(can1.width, can1.height);

This particular code will only function properly if the width is equal to the height. The issue lies in plotting points above and below the line y=x. As we know, y=x represents a straight line with an equation of y=mx+c where m equals 1 and c equals 0. In order to plot a line, we need two distinct points. With ctx.lineTo, it always begins at (x,y) = (0,0), which is the top left corner. When the width and height vary, errors will occur. The solution provided employs the Math.min function to ensure the line is plotted with x=y. However, I recommend utilizing the Math.max function instead so that all points fall within the maximum value of both x and y, as long as they are less than the width and height provided.

ctx.lineTo(Math.max(can1.width, can1.height), Math.max(can1.width, can1.height));

For those interested in running the complete code and observing the outcome, please refer to the link below:

https://gist.github.com/harisnp/320462ab20eafd3f36826bee6458ac8c

Take a look at the result using the Math.max approach below:

https://i.sstatic.net/iyLtc.png

Answer โ„–3

Utilize the cross product method.

The code snippet provided below determines whether a point lies to the left, right, or on a specific line by using the cross product calculation.

// x1, y1 represent the starting point of the line
// x2, y2 represent the end point of the line
// px1, py1 represent the point to be tested
function testPointToLine(x1, y1, x2, y2, px1, px2){
    return (x2 - x1) * (py1 - y1) - (y2 - y1) * (px1 - x1);
}

If the line always originates from 0,0, you can simplify the function as follows:

function testFromOriginPointToLine(x2, y2, px1, px2){
    return x2 * py1 - y2 * px1;
}

Both functions essentially calculate the cross product between the line vector and the vector from the line's start to the given point.

The Adjustment

To ensure that the canvas orientation does not affect the calculations, modify your point function as shown below:

function Point(x, y){
    this.x = x;
    this.y = y;
    this.label = canvas.width * y - canvas.height * x <= 0 ? 1 : -1;
}

An Illustrative Example

requestAnimationFrame(addPoints);
const ctx = canvas.getContext("2d");

 // Random number generator function
const rand = (min=1,max=min+(min=0))=>Math.random()*(max-min)+min;   

function sizeCanvas() { // Set canvas dimensions
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    ctx.strokeStyle = "white";
    ctx.lineWidth = 3;
    ctx.lineTo(0,0);  
    ctx.lineTo(canvas.width, canvas.height);
    ctx.stroke();
}

function drawPoint(point){
    ctx.fillStyle = point.label > 0 ? "red" : "#0F0";
    ctx.beginPath();
    ctx.arc(point.x, point.y, 4, 0, Math.PI * 2);
    ctx.fill();
}

function Point(x, y) {
    this.x = x;
    this.y = y;
    this.label = canvas.width * y - canvas.height * x <= 0 ? 1 : -1;
}

function addPoints(){
    if (canvas.width !== innerWidth || canvas.height !== innerHeight) { sizeCanvas() }
    drawPoint(new Point(rand(canvas.width), rand(canvas.height)));
    requestAnimationFrame(addPoints);
}
canvas {position: absolute; top: 0px; left: 0px; background: black;}
<canvas id="canvas"></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

Setting the width of an image within an iframe: A step-by-step guide

Is there a way to adjust the width of an image within an iframe? Typically, if an image with high resolution is placed inside an iframe, the iframe becomes scrollable by default. ...

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "รค" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

Similar to session_start() and $_SESSION in Node.js/Express

I'm on a quest to discover the equivalent of session_start() and $_SESSION in Node.js/Express so I can store the current user's id in the session. Most tutorials and videos recommend using express-session, but I've come across a warning: ...

Guide to dynamically assigning the id attribute of an HTML element using angularjs (1.x)

Given an HTML element that is a div, what is the method to assign a value to its id attribute? The value should be a combination of a scope variable and a string. ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

Can Typescript Be Integrated into an AngularJS Application?

I have been thinking about the optimal timing and scenario to implement Typescript in an AngularJS project. While I have come across examples of TS being used in a Node, Express, Mongo backend, I am particularly intrigued by how well TS integrates with A ...

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Mastering the Vue 3 Composition API: A guide to efficiently utilizing it across multiple Vue instances spread across different files

tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file? I incorporate Vue to improve user interactions on specific pages like t ...

Choose a specific inner div element within another div using jQuery

Trying to target a specific div within another div in my HTML structure. Here's how it looks: <div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div> I am attempting to select #cube ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

Solution: Resolve clientY scrolling issue within an HTML document

I am facing an issue with the positioning of my context menu. When I right-click and scroll down, the menu does not maintain its regular position. Instead of appearing to the right of the mouse cursor when stationary, it moves below the cursor based on how ...

Encountering an issue with my node configuration while working on a Discord bot

Attempting to develop my own Discord Bot has presented me with a challenging error that I am struggling to resolve: internal/modules/cjs/loader.js:968 throw err; ^ Error: Cannot find module './commands/${file}' Require stack: - C:\Users&bso ...

Using a for loop in JavaScript to dynamically display TextBoxFor(model=> model[i].prop) in an MVC application

I need some help getting this code to function correctly: $('#ddl').change(function () { $('#cont').html(''); var count = getCount($('#ddl').val()) for (var i = 0; i < count ; ...

Dealing with an Ajax request that returns a file or partial HTML in the event of an error - what is the best approach?

Imagine a scenario where we are engaged in a dialogue with certain settings. Upon clicking the "OK" button in the dialogue, the settings are transmitted to a controller function through an AJAX call. This call may either yield a downloadable file or an err ...

What could be causing my component to fail to load properly with Vite?

I have been working on a React project using Vite. Following a tutorial I discovered in an article at https://www.digitalocean.com/community/tutorials/how-to-set-up-a-react-project-with-vite, I encountered an issue. Despite following the tutorial step by ...

Unable to trigger the show_popup function by clicking the button

Why won't this piece of code function as expected? <script src="web_push.js"></script> <body> <button onclick="show_popup()"> Button </button> </body> The content of web_push.js file is shown below ...

Retrieving a value in the app component from a map using Angular

I have been struggling to display the values of ValueM, ValueR, and product in my app.component.html file. Can anyone offer a solution or tip to help me move forward? Thank you very much. app.component.ts forkJoin( this.service1.method1(filter1), ...

ng-hide is not functioning to display the form

I'm trying to display a form using ng-if when the "add" button is clicked, but it's not working. I've looked at several examples and tried them all, but none have worked for me. Here is the code I am using: angular.module('myFormApp&ap ...

Using MySQL data in an EJS file to create a personalized Profile Page

In the midst of a personal project aimed at honing my web development skills and gaining a deeper understanding of the intricacies of the field, I have hit a roadblock. The focus of this project is to create a profile page, and while I have successfully co ...

Keeping state between navigations in Ionic and AngularJS: A guide

In the process of developing my very first hybrid mobile application using Ionic and AngularJS, I have encountered a challenge that I am currently trying to resolve. The issue at hand involves maintaining the state of the graphical user interface between n ...