Position is at the highest & leftmost point, with a rotation created by the

I need help with JavaScript code that can arrange playing card images in a specific layout, as shown in the attached image. I've been trying to use CSS transform rotate with a 7-degree angle, but I'm having trouble calculating the correct left and top positions to achieve the desired result.

Answer №1

To position the cards, you must apply a CSS transform to them. Initially, each card requires a rotation transformation around the transform-origin located at the lower right corner. Therefore, you must determine the rotational angle for each card (by adding an angle of 7deg or another degree). Next, you need to shift each card so that they form a path, resembling an ellipse as depicted in your image. Define an ellipse with horizontal and vertical radii (a and b), increase the rotation angle (around the center of the ellipse), and compute the x and y coordinates of the point on the elliptical path using the following formula (based on polar coordinates equations):

x = a * cos(alpha);
y = b * sin(alpha);

The dx and dy values (the difference between the current and previous x and y respectively) must be calculated and accumulated for use in the translate transformation.

Below is a demonstration of the code:

JS:

var n = 13; // number of cards
var al = 7; // angular difference between two cards
var a = 90; // horizontal radius of the elliptical path for card arrangement
var b = 200; // vertical radius of the elliptical path for card arrangement
var step = 4; // degree interval to move between cards along the elliptical path

// Define initial angles and variables
var initAlpha = (180 - al * (n - 1)) / 2;
var beta = (180 - step * (n - 1)) / 2 - 15;
var betaRad = beta * Math.PI / 180;
var prefixes = ["webkit", "moz", "ms", ""];
var x = a * Math.cos(betaRad), y = b * Math.sin(betaRad);
var dx = 0, dy = 0;

// Function to perform transformations
function transform(elem, dx, dy, da) {
    for(var i = 0; i < prefixes.length; i++){
        elem.style[prefixes[i] + (prefixes[i] ? "Transform" : "transform")] = "translate(" + dx + "px," +
            dy + "px) rotate(" + da + "deg)";
    }
}

for(var i = 0; i < n; i++) {    
    var card = document.createElement("div");
    card.className = "card";
    document.body.appendChild(card);     
    transform(card, dx.toFixed(10), dy.toFixed(10), initAlpha);    
    beta += step;   
    initAlpha += al;
    betaRad = beta * Math.PI / 180;
    var x2 = a * Math.cos(betaRad);    
    var y2 = b * Math.sin(betaRad);
    dx += x - x2;
    dy += y - y2;    
    x = x2;
    y = y2;    
}    

CSS:

.card {
  width:150px;
  height:100px;
  border:1px solid gray;
  border-radius:5px;
  position:absolute;
  top:200px;
  left:30px;
  -webkit-transform-origin:right bottom;
  -ms-transform-origin:right bottom;
  -moz-transform-origin:right bottom;
  transform-origin:right bottom;
  background:lightyellow;
  transition:background 0.3s;
}
.card:hover {
  background:orange;
}
body {
  background:black;
}

View Demo

Please note that while the arranged cards may not be exactly like the image shown, they closely resemble it. You can adjust parameters such as the number of cards (n), angular differences al, horizontal radius a, vertical radius b of the elliptical path, step, initAlpha, beta to modify the card layout.

For a more perceptible demo allowing you to input text for the card without unexpected directional issues, check out this alternate demonstration.

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

What is the best practice for preloading route data before navigating to the route?

When preparing to render a page for a specific route, my goal is to fetch the necessary data synchronously first. Ideally, I prefer to handle the data fetching within the page component, but I am open to doing it in the router files as well. I have experim ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...

Navigating through a jQuery array while utilizing the $.inArray method

Below is an example of my Array that I am working with, retrieved from a successful jQuery .post call: data = JSON.parse(data); $(".chk_permission_").each(function() { if ($.inArray($(this).val(), data)) { $(thi ...

Unique form validation process: utilizing JSON

Attempting to validate JSON input using Angular's FormControl. The typical approach, such as validating an email address, would involve: <form name="form"> <textarea ng-model="data.email" type="email" name="email"></textarea> &l ...

Encountering a Type Error in React Native when attempting to create a 3D cube with Three.js

Following a tutorial on creating a simple app that displays a 3D cube, I encountered an issue with my code: import React from 'react' import {View} from 'react-native' import Expo from 'expo' import {Scene, Mesh, MeshBasicMate ...

"Concealing Querystrings in Node.js and AJAX: A Step-by-Step

I want to create a simple login form using the ajax Post method. However, I am having issues with the querystring still appearing in the URL. Can anyone help me resolve this issue? Thank you for any assistance! [ https://i.stack.imgur.com/R76O4.png http ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

Leveraging UseRouter.query Data in Next.js Content Display

I'm currently diving into routing in Next.js and running into an issue where the query values are not being included in the HTML response. Despite recognizing that isReady is false and the return is happening before the variables are set, I'm uns ...

The issue with CSS and JavaScript is causing the appended elements to not display properly in PHP code

I am currently facing issues with retrieving the grandchildren from my database table named referrals. Surprisingly, my code successfully retrieves the username of my grandchildren, but it does not display below the line of my child and there are no errors ...

Utilizing Angular 6's Mat-Table in a dynamic way

I am currently working on an Angular application that involves displaying data fetched from an API. The challenge I'm facing is that I do not have prior knowledge of the data I will be retrieving. Additionally, I need to create a model that can be use ...

Utilizing JSON and AJAX for data parsing

I have a PHP page that contains the following code: <?php $library= '{"closets":[ {"id":"001","theme":"literature","shelves": { ...

Guide to creating a line break with a break tag in HTML and copying it to the clipboard

Is it possible to copy text to the clipboard and have it appear on a new line? When I click the copy button and paste the text (on a post, website, blogger, forum, notepad, etc.), I want it to maintain its original formatting. Here is how the text looks b ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Convert JavaScript objects into HTML format

Alright, I've got some JavaScript that's fetching data from a JSON file through a URL. Now, my goal is to convert each object (author_name, rating, author_url) into JavaScript IDs so that I can easily reference them in my HTML. For instance: &l ...

Exploring multidimensional JSON arrays with the jQuery each() method

What am I missing here? The first iteration works fine, but it breaks in the second one.. var testJSON = {"cluster":[{"node":[{"name":"one", "number":'100', "error":"none"},{"name":"two", "number":'200', "error":"none"},{"name":"three ...

Quirks of Emscripten Exported Functions in Visual Studio

As I start delving into Emscripten, I've encountered a puzzling issue with exporting functions for use in JavaScript. Working on a test project involving libsquish, the specific details aren't crucial to my question beyond the header/code filenam ...

Utilize the "don't get terminated" app

Currently, I am working on implementing a middleware in my application to check for the presence of a token on all routes. For testing purposes, I have decided to focus on the /users route. In order to achieve this, I made the following adjustments to my a ...

What is the reason for not being able to align breadcrumb text to the right

This section contains HTML code and CSS for a breadcrumb container. The issue is that the breadcrumb is currently displayed on the left side. How can the breadcrumb be right-aligned? .breadcrumb-container { font-family: "Work Sans", sans-serif; ...

Tips for organizing an event using AngularJS within a set timeframe

My goal is to compare the current time with a specified start and end time in order to display a message on the page when the current time falls within that range. For example, let's say startTime = 10:30 AM and endTime = 1:30 PM. How can I achieve d ...