What could be causing the incorrect value of the endpoint of an element when utilizing a function?

By adding angles individually and then using ttheta (without calling a function to add angles and then using ttheta), the problem is resolved. However, can anyone explain why using a function here is incorrect or identify the issue that this function is causing?

The solution involves the following code:

    dtransform = window.getComputedStyle(leg1, null).getPropertyValue("transform");
    values = dtransform.split('(')[1].split(')')[0].split(',');
    dtheta = Math.round(Math.atan2(values[1], values[0]) * (180 / Math.PI));
    dtransform1 = window.getComputedStyle(leg2, null).getPropertyValue("transform");
    values1 = dtransform1.split('(')[1].split(')')[0].split(',');
    dtheta1 = Math.round(Math.atan2(values1[1], values1[0]) * (180 / Math.PI));

    ttheta = dtheta + dtheta1;

Instead of using a function.

The goal is to determine the endpoints of an element when it is rotated from the left and top of the browser.

https://i.sstatic.net/0MmGg.png

The X & Y values represent the maximum distance of the endpoints of the shoe

At some points, I get the correct values and at others, I get incorrect values. I attempted to add the angle from the parent element, but this did not resolve the issue.

I sought assistance from the related answer mentioned here

To verify if the values are correct or incorrect, I added an event to capture the clientX of a mouse click. The values of element positions are recorded when the Try button is clicked.

Am I making a mistake? Any insights provided would be greatly appreciated

let leg1 = document.querySelector(".Leg1Shoe")
let leg2 = document.querySelector(".Leg1Part")
let animeAll = document.querySelectorAll(".allClass")
let animePause = false

let ttheta = 0;

function getPos() {
  if (!animePause) {
    animeAll.forEach(e => {
      e.classList.add("AnimatePaused");
    })
    animePause = true;
  } else {
    animeAll.forEach(e => {
      e.classList.remove("AnimatePaused");
    })
    animePause = false;
  }

  let h, w, x, dx, tx, y, dy, ty = "";
  leg1.style.outline = "1px solid red"
  h = leg1.offsetHeight;
  w = leg1.offsetWidth;
  x = leg1.getBoundingClientRect().left;
  y = leg1.getBoundingClientRect().top;
  func2(leg2);
  func2(leg1);
  dx = (Number(h * (Math.sin(ttheta * (Math.PI / 180)))) + Number(w * (Math.cos(ttheta * (Math.PI / 180)))).toFixed(2);
  dy = (Number(w * (Math.sin(ttheta * (Math.PI / 180))) + Number(h * (Math.cos(ttheta * (Math.PI / 180)))).toFixed(2);
  tx = (Number(x) + Number(Math.abs(dx))).toFixed(2);
  ty = (Number(y) + Number(Math.abs(dy))).toFixed(2);
  console.log("X:" + tx, "Y:" + ty);
}

function func2(e) {
  let dtransform, dtheta, values = "";
  dtransform = window.getComputedStyle(e, null).getPropertyValue("transform");
  if (dtransform != "none") {
    values = dtransform.split('(')[1].split(')')[0].split(',');
    dtheta = Math.round(Math.atan2(values[1], values[0]) * (180 / Math.PI));
  } else {
    dtheta = 0;
  };
  ttheta = Number(ttheta) + Number(dtheta);
}

leg1.addEventListener('click', mousePos);

function mousePos(e) {
  console.log("X:" + e.clientX, "Y:" + e.clientY)
}
.Leg1Part {
  position: relative;
  left: 100px;
  top: 43px;
  width: 20px;
  height: 75px;
  background-color: green;
  transform-origin: top center;
  animation: animateLeg1Part 5.0s linear infinite alternate;
}

@keyframes animateLeg1Part {
  0% {
    transform: rotate(40deg);
  }
  25% {
    transform: rotate(25deg);
  }
  50% {
    transform: rotate(10deg);
  }
  75% {
    transform: rotate(30deg);
  }
  100% {
    transform: rotate(60deg);
  }
}

.Leg1Shoe {
  position: absolute;
  left: 0px;
  top: 73px;
  width: 40px;
  height: 20px;
  background-color: blue;
  transform-origin: center left;
  animation: animateLeg1Shoe 5.0s linear infinite alternate;
}

@keyframes animateLeg1Shoe {
  0% {
    transform: rotate(15deg);
  }
  50% {
    transform: rotate(-20deg);
  }
  100% {
    transform: rotate(30deg);
  }
}

.AnimatePaused {
  animation-play-state: paused;
}
<div class="Leg1Part allClass">
  <div class="Leg1Shoe allClass"></div>
</div>
<button onclick="getPos()">Try</button>

Appreciate the help in advance

Answer №1

This response does not provide a definitive solution but rather serves as a general guideline for the process you can undertake.

  1. Retrieve the transformation matrices for the "leg" and the "shoe" as you normally would by utilizing the getPropertyValue("transform") function. This will yield a string similar to:
    matrix(-0.568718, 0.822533, -0.822533, -0.568718, 0, 0)
    , representing a condensed version of a 3x3 transformation matrix:
| cos(theta) -sin(theta) 0 |
| sin(theta) cos(theta)  0 |
| 0          0           1 |
  1. Parse the string and construct a 2D array for this matrix. Note: since there are no translations (two zeros in the last column), operations can be performed on 2x2 matrices.

  2. Multiply the transformation matrices for the "leg" and the "shoe" together. This can be a complex process, and the mathjs library may be useful.

  3. Apply the resulting transformation matrix to the vector of each original point's coordinates. This will provide the adjusted coordinates of the point considering all rotations.

For further information, please refer to the following resources:

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

CSS Animations as an Alternative to jQuery's fadeIn(), fadeOut(), and fadeTo() Functions

I currently have the following code snippet: $('#button1').click(function(){ $('#header_bg').fadeTo(15, 0, function() { document.getElementById('header_bg').style.fill = '#FF0000'; }).fadeTo(&ap ...

Experimenting with a customizable Vue.js autocomplete feature

Check out this sample code: https://jsfiddle.net/JLLMNCHR/09qtwbL6/96/ The following is the HTML code: <div id="app"> <button type="button" v-on:click="displayVal()">Button1</button> <autocomplete v- ...

The contrastText property of the MUI React Theme palette is not functioning properly

I am working with MUI React to design a menu and I have utilized the AppBar component. I would like to customize it in the following way: brown.myBrown = '#544846'; const brownTheme = createTheme({ palette: { primary: { ma ...

The PDF format is experiencing compatibility issues when used with the CSS property for page breaks after:

My PDF with CSS page breaks is not functioning properly, as the pages are not breaking as intended. Removing position:absolute solves the issue but leaves space after each page. I suspect it may be a CSS problem, but I'm unsure. If the issue lies wit ...

Transforming a text file into an array using fs in Node.js

My text file contains the following: {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"select","nombre":4} Is there a way to convert the text file contents ...

What could be causing me to see a basic checkbox instead of a toggle switch in my React application?

I've been attempting to create a toggle switch that activates dark mode using Bootstrap switches, but when I save the code, it reverts back to a basic checkbox. According to the documentation, for older assistive technologies, these switch elements wi ...

Tips for validating date input in a TextBox using JQuery on an ASP.NET platform:

Here is some code I wrote: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="datetime.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <tit ...

Stop iframes on iOS from automatically adjusting their height based on the content within them

Update: I recently discovered that Apple quietly prohibits fixed-size iframes in iOS. How frustrating! What can be done to make an IFrame responsive in iOS Safari? I am facing a seemingly straightforward task: embedding a fixed-size <iframe> within ...

What is the easiest way to modify the color of a basic PNG image in a web browser?

While working on a website project, I encountered instructions for mouseover styles in the design that got me thinking: It's straightforward to achieve with javascript or css image swapping... but here's the catch. There will be multiple icon li ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

Failed Cross-Origin Request Sharing in AngularJS 1.4

I'm currently working with AngularJS version 1.4.3 and here is the code snippet I am using: angular .module('app', []) .run(run); function run($http) { a = $http({ method: "GET", url: 'http://127.0.0 ...

Manipulating and filtering an array of objects in JavaScript/jQuery

Looking to simplify my array manipulation in Javascript, I need to subset based on key-value matches. I have an array called js_obj, and my goal is to modify objects where a certain condition is met. Consider the structure of my array: js_obj = [{ wo ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

What are the steps to implementing PNG masking using PixiJS?

I am currently working on incorporating a png sprite as a mask for another layer. I found a demo on the pixi.js official website and created this fiddle: https://jsfiddle.net/raphadko/ukc1rwrc/ The code snippet below is what I am using for the masking fu ...

Ways to prevent the jQuery simple slider from transitioning slides while it is in an invisible state

There is a jQuery slider on my website that behaves strangely when I navigate away from the Chrome browser and return later. It seems to speed through all pending slides quickly when it was not visible. Now, I want the slider to pause when it becomes invi ...

What is the best way to position an image in the center of the screen with uniform margins around it?

Could someone please help me figure this out? I've been attempting for some time but can't seem to make it work with the bottom margin. This website in the fashion industry showcases what I'm trying to achieve: It's designed to be resp ...

Utilizing Vue.js for enhanced user experience, implementing Bootstrap modal with Google Maps autocomplete

I recently set up a Bootstrap modal that includes an <input>. To enable Google autocomplete for it, I utilized the commonly known trick below: .pac-container { z-index: 10000 !important; } However, I have encountered difficulty in getting the a ...

The error message InvalidCharacterError is displayed when the attempt to create a new element using the 'createElement' method on the 'Document' object fails. This is due to the tag name provided ('/static/media/tab1.fab25bc3.png') not being a valid name

Hey everyone! I'm new to using React and I decided to try cloning Netflix by following a tutorial on YouTube. However, I've encountered an issue with rendering an image in a functional component. The error message I'm receiving is as follow ...

What are the steps to adjust the size of the Facebook "like" button?

Is there a way to modify the size of the Facebook like button? I attempted to adjust the padding of <a class="connect_widget_like_button clearfix like_button_no_like"> using jQuery, but was unsuccessful. Any suggestions on how this can be achieved? ...