What is the best way to move the ball within a ruler chart that spans from -100 to 100 while staying within the confines of the canvas?

Looking at a graph with measurements from -100 to 0 and 0 to 100, I am facing a challenge in adjusting the ball's position calculation based on the gradientDataChart input. This input can have a value between -100 and 100, but the issue lies in proportionality; depending on the screen size, the ball keeps disappearing. Initially, I used a distance of 16, which worked well for a width of 586px.

To explore this further, I ran some tests here.

In the code snippet provided, setting 38 for 900 pixels width seemed to work fine. However, when I tried it with 1000 pixels, the positioning got completely off track... It definitely needs to be responsive:

var widthDefault = 900, metric = -100, calcPos = 38 * ((metric / widthDefault) * 100);
      ctx.beginPath();
      canvas.width = widthDefault;
      ctx.translate(calcPos, 0);
      var centerX = canvas.width / 2; 
      var centerY = canvas.height / 2;
      ctx.arc(centerX, centerY, 24, 0, Math.PI * 2, false);
      ctx.fillStyle ="#ffffff";
      ctx.fill()
      ctx.font = 'bold 14pt sans-serif';
      ctx.textAlign = 'center';
      ctx.strokeStyle ='#622BCF'
      ctx.stroke();
      ctx.fillStyle ="#622bcf80"; 
      ctx.fillText(`${medida}`, centerX, centerY+8);
      ctx.globalCompositeOperation = 'destination-over';

Here is an image example: https://i.sstatic.net/c78vS.png

Answer №1

When working on your calcPos function, make sure to account for proportionality by dividing the width by the number of points. With a range from -100 to 100, we have a total of 200 points that need to be multiplied by the position, which in this case is metric + 100.
X = width/200 * (metric + 100)

Feel free to experiment with the following code:

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

function drawCircle(width, metric) {
  var X = width/200 * (metric + 100)
  var Y = canvas.height / 2;
  ctx.beginPath();
  ctx.arc(X, Y, 18, 0, Math.PI * 2, false);
  ctx.stroke();
  ctx.fillText(metric, X, Y);
}

drawCircle(canvas.width, -80)
drawCircle(canvas.width, -50)
drawCircle(canvas.width, 0)
drawCircle(canvas.width, 25)
drawCircle(canvas.width, 80)
<canvas id="c" width=300 height=140 style="border:solid 1px"></canvas>


Using the same code but altering the canvas width:

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

function drawCircle(width, metric) {
  var X = width/200 * (metric + 100)
  var Y = canvas.height / 2;
  ctx.beginPath();
  ctx.arc(X, Y, 18, 0, Math.PI * 2, false);
  ctx.stroke();
  ctx.fillText(metric, X, Y);
}

drawCircle(canvas.width, -80)
drawCircle(canvas.width, -50)
drawCircle(canvas.width, 0)
drawCircle(canvas.width, 25)
drawCircle(canvas.width, 80)
<canvas id="c" width=600 height=140 style="border:solid 1px"></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

Tips for sending the information from a select dropdown in a Redux form to the backend API using Redux

In my Redux form, I have two input fields and one select drop-down. I am successfully storing the values of the inputs to a backend API, but I am having trouble getting the select drop-down value to pass it to the server. I suspect there might be an error ...

Every checkbox on the Angular 6 platform has been chosen

In my model class named processAnexOne.ts, I have the following structure: export class ProcessAnexOne { documentList: string; } Within the component class, I have initialized an instance as follows: export class ProcessAnexOneComponent implements O ...

In React, how can I re-render only the component that I clicked on?

Trying to create a color matching game using React - players need to find matching images. Encountering an issue where clicking on one card causes all other cards to re-render. How can this be avoided? //app component handleClick = index => { this ...

Express.js Routes with Prefix

Is it possible to add a prefix to only certain routes in express.js? I understand that using app.router() allows for adding a mount point, but this applies to all routes. I'm interested in finding a method to insert /api/v1/ before several routes wit ...

What can I do to stop a webpage from automatically refreshing when I submit a form?

I'm currently in the process of building my very first website, and I've run into a bit of a snag that I can't seem to figure out. Whenever a user tries to add an item to the cart or increase the quantity, I want to avoid the page refreshing ...

How can you choose multiple options in a Select2 dropdown when it first loads?

I'm having trouble correctly loading a JSON array of selected items into an existing select2 dropdown. I want certain items to be pre-selected when the page loads, but I'm struggling with the syntax. Consider the following JSON array, stored in ...

Using JavaScript to interact with HTML select elements on iOS devices

Although I'm not getting my hopes up, I thought I'd ask anyway. I am interested in using JavaScript to open a select element on mobile Safari for iPhone or iPad. After a thorough search on Google and Stack Overflow, it seems that many people sh ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

Best practices for securing string values in Node.js

Looking to retrieve the IP address with nodejs/express. Check out the code snippet below that accomplishes this: const ipAddress = String(req.ip || "unknown"); Considering that req.ip is pulled from an HTTP header, there's a potential risk ...

Guide on transferring three js variable to an HTML label element

For my project, I am looking to pass three js values to the label of a div. The desired output is: stWay: stProposer: stTime: hello John 2017-09-07 I have successfully programmed a button to make div1 a ...

What is the best method for transforming a base64 encoded string into a base64 formatted PDF string?

Could someone please help me with a problem I'm facing? I am utilizing an AngularJS .pdf viewer that displays documents in a modal using base64. Everything works smoothly when the base64 is generated from a .pdf file. The backend (Java) generates th ...

Fixing the TypeSrcipt error "Object is possibly 'undefined'" while using virtual mongoose attribute can be achieved by carefully handling null or undefined values in your code

When attempting to calculate a virtual property model, I encounter the error message: Object is possibly 'null'. I would prefer not to suppress TypeScript's strict rule if possible. import { Schema, model } from "mongoose"; const ...

Is there a distinction in functionality when utilizing fat arrow syntax versus traditional syntax for ES6 class methods and React?

Consider these two examples showcasing different ways to write an ES6 class method: The first example uses the non-fat arrow, or concise method syntax: class Test extends Component { handleClick() { return 'clicked' } } The second exam ...

Troubleshooting TypeScript Node.js Compilation Issue

In my quest to establish a debugging environment for a project from 2019, I included the following script in my package.json: "dev:debug": "tsc-watch --onFirstSuccess \"node --inspect -r ts-node/register src/app.ts\"", Executing this script pro ...

Angular 2 release 6 has encountered an issue with the hidden functionality not functioning properly

I'm experiencing an issue with a div element that has a [hidden] attribute. It's not working as expected. I want the div to be hidden when the cartItems array is empty, but it's not hiding. Just to mention, I am also using bootstrap in my pr ...

Error: Webpack module is not a callable function

I have been developing a backend system to calculate work shifts. I am currently facing an issue with posting user input using a module located in services/shifts. While the getAll method is functioning properly, I encounter an error when trying to post da ...

beforeprinting() and afterprinting() function counterparts for non-IE browsers

Is there a way to send information back to my database when a user prints a specific webpage, without relying on browser-specific functions like onbeforeprint() and onafterprint()? I'm open to using any combination of technologies (PHP, MySQL, JavaScr ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Converting a time string into a date object using JavaScript and AngularJS

After receiving the string from the REST API as "20160220", I am aiming to format it as "20/02/2016". Utilizing AngularJS for this task, I understand that I will need to implement a filter. I have already attempted the code snippet below: app.filter(&apo ...

What is the best way to implement a CSS Style specifically for a glyphicon icon when it is in keyboard focus?

I have a particular icon representing a checkbox that appears as a glyphicon-star. It is designed to display in yellow when focused on by the keyboard navigation. This feature is intended to help users easily identify their location on a page. However, an ...