What is the process for spinning a span in the center of an image?

My canvas displays an image:

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

There is a white square with a refresh icon on the right side of the image, slightly hidden by a black circle. I implemented it like this:

var rotatorSpan = document.createElement("span");
rotatorSpan.id = _this.idRotator;
rotatorSpan.className = "glyphicons glyphicons-restart";

document.getElementById("canvas-overlay").appendChild(rotatorSpan);

In the draw function:

this.drawRotator = function() {
    var pivotX = _this.x + (_this.imageWidth / 2);
    var pivotY = _this.y + (_this.imageHeight / 2);
    var radius = Math.sqrt(Math.pow((_this.x - pivotX), 2) + Math.pow((_this.y - pivotY), 2));
    var rotatorX = _this.x + (_this.imageWidth / 2) + radius;
    var rotatorY = _this.y + (_this.imageHeight / 2) + (_this.indicatorRadius / 2);

    _this.ctx.save();
    _this.ctx.translate(pivotX, pivotY);
    _this.ctx.rotate(_this.rotation);
    _this.ctx.translate(-pivotX, -pivotY);
    _this.ctx.beginPath();
    _this.ctx.arc(rotatorX, rotatorY, this.indicatorRadius, 0, Math.PI * 2, false);
    _this.ctx.closePath();
    _this.ctx.fill();
    _this.ctx.restore();

    document.getElementById(_this.idRotator).style.position = "absolute";
    document.getElementById(_this.idRotator).style.top = rotatorY + "px";
    document.getElementById(_this.idRotator).style.left = rotatorX + "px";
    document.getElementById(_this.idRotator).style.fontSize = "1em";
    document.getElementById(_this.idRotator).style.backgroundColor = "#fff";
    document.getElementById(_this.idRotator).style.border = "1px solid #000;";
    document.getElementById(_this.idRotator).style.zIndex = 1000;
    document.getElementById(_this.idRotator).style.transform = "rotate(" + _this.rotation + "rad)";
};

When I rotate the image:

https://i.sstatic.net/72nON.png

You can see that everything rotates except the white square with the refresh icon. It rotates around its own center point.

How can I make the white square (span element I created) rotate around the center point of the image?

Answer №1

One way to specify the center of rotation is by using the CSS property transform-origin. Check out this demonstration to see it in action. Keep in mind that this feature may not be supported in older web browser versions. For more information, you can visit this link.

@-webkit-keyframes rotating /* Safari and Chrome */ {
  from {
    -ms-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -ms-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes rotating {
  from {
    -ms-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -ms-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
.square{
    background:black;
    width:30px;
    height:30px;
   -webkit-animation: rotating 2s linear infinite;
  -moz-animation: rotating 2s linear infinite;
  -ms-animation: rotating 2s linear infinite;
  -o-animation: rotating 2s linear infinite;
  animation: rotating 2s linear infinite;
        -webkit-transform-origin: 100px 100px;
    
}
<div class="square"></div>

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

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Create a JavaScript function without attaching it to the global window object

Can someone please help me with defining a function and using it inside Jquery within the $(document).ready block? function addLeadingZero(number) { return (number < 10 ? '0' : '') + number } I'm not confident that I ha ...

What are some ways to disable text selection when working with VueJS?

Let's say I have a component that displays some text. When I click on the text at the beginning and then shift-click on another part, the text between those two points gets selected. Is there a way to prevent this behavior using only VueJS? ...

Dealing with a Promise and converting it into an array: a step-by-step

I am encountering difficulties progressing with my Promise returned from the getPostedPlaces() function. After executing getAll(), an Array is displayed as shown below. Although the array appears to be correct, I am unsure how to make the getAll() function ...

Navigating with Angular: Understanding ng-view and Routing

How does Angular understand which template view to request containing the 'ng-view' element? If I directly navigate within my application to http://localhost/Categories/List/accessories , a request is still sent to '/' or the index ...

Creating a mouse-resistant div with a magnet-like effect

Looking for a way to make a circle move like a magnet effect when the mouse is near, causing elements underneath it to be exposed. If you want to see an example, check out this fiddle link: http://jsfiddle.net/Cfsamet/5xFVc/1/ Here's some initial c ...

Ways to add space around the td element and properly align the content within it

I've recently delved into the realm of web development, and I'm encountering some challenges with HTML alignment. Despite exploring various resources and attempting to utilize align="left"/right/center attributes, I'm still struggling to ach ...

AngularJS Multiple Select fails to display preselected options

This morning, I dedicated a significant amount of time to finding a solution for assigning multiple values to an entity on my form. The scenario is as follows: I have an Entity named QualityData that can have various MechanismIdentifiers. After brainstor ...

Learning the basics of JavaScript: Displaying the last number in an array and restarting a function

Hey there, I'm diving into the world of JavaScript and have set myself a challenge to create a simple bingo number machine. Check out my CodePen project here. I've successfully generated an array of 20 numbers, shuffled them, and added a marker t ...

What is the best way to update the state by either adding to it or replacing it if the key

I'm currently working on a project involving radio buttons and I need to create dynamic state by setting the initial state on the first click, then updating it with subsequent clicks by either concatenating the new value onto the existing state or rep ...

Switch the class of a div using jQuery when it is clicked

I need to implement functionality where 4 different links change the class of a specific div when clicked. For example, clicking on link 1 will change the class to s1, link 2 to s2, and so on. Below is some code that I have been working on, however, I am ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Instructions on how to insert a new row into Datatables following the successful submission of a form via AJAX请求

Could someone please provide guidance on how to insert a new row into an existing datatable after a successful AJAX request? Here is the code I am currently using: $(document).ready(()=>{ $.ajax({ url: 'http://localhost:3000/api/post/getUserDat ...

Can you help me with sorting asynchronous line points for KineticJS?

For the past couple of days, I've been grappling with a peculiar issue that I found difficult to articulate in the title. The challenge I'm facing involves a KineticJs Line, which contains an array of points (line.attrs.points) represented as ob ...

Having trouble with the expand feature of Bootstrap 5 navbar

I am facing an issue with my Bootstrap 5 navbar as it only extends as wide as the contents within it. I want the navbar to expand the entire length of the container but changing the navbar-expand-?? setting doesn't seem to have any effect. https://i.s ...

What is the best way to center this menu on the web page?

Is there a way to center this menu on the web page for better alignment? Any suggestions on improving the code are welcome. Thank you in advance. Edit: Also, how can I modify the hover effect to change the background color to green and make it expand full ...

The error message "global.HermesInternal - Property 'HermesInternal' is not found in the type 'Global & typeof globalThis'" appeared

I ran the auto-generated code below: $ react-native init RepeatAloud App.tsx /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local * ...

Encountering an issue with WebDriver in the realm of JavaScript

I am struggling to use JavaScript to locate specific controls and send values to them. One example is changing the text in a textbox with the ID "ID" to "123456". Below is the code I tried: ((IJavaScriptExecutor)driver).ExecuteScript("document.getElement ...

How does the designated callback function in the filter method effectively remove any missing values from the array?

//Snippet of JavaScript code let sparseArray = [5, , 3, , 1]; let denseArray = sparseArray.filter(() => true); console.log(denseArray); The filter function in the callback removes empty elements from the sparse array. Output: [5, 3, 1] Explanation: ...

Navigating a list using AngularJS within an HTML view: tips and tricks!

Implementing AngularJS within the context of the Ionic framework. The $scope on the front-end consists of: an object User that contains a list of sports: $scope.user = { sports: { "running": true, "football": true } } a list named "matches" containing u ...