Pablo
Pablo

Reputation: 1435

Animate image arrow like speedometer in JS

I have this current UI

enter image description here

The arrow image is just a transparent image.

I'm trying to add animation on that image.

it will just move from low to high for every page reload / after the page being loaded.

My idea to do this is using jquery

I'm playing around with this code

 <img class="meter-arrow" src="{!! url('public/images/arrow.png') !!}" >
  
  <script src="{{url('public/js/libraries/jquery_file_3_1.js')}}"></script>
  <script>
    $(".meter-arrow").animate({left: '250px'});
   </script>

Source: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation1

Is it possible to do this

Upvotes: 0

Views: 442

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

It is strangely quite hard to animate a rotation using jQuery. See here about how.

I think it is easier in plain JS:

// The image element
let arrow = document.querySelector(".arrow")

// It onload --rotation value
let rotation = parseInt(getComputedStyle(arrow).getPropertyValue("--rotation"))

// Rotation on an interval
let increase = setInterval(function(){
  rotation = (rotation>25) ? clearInterval(increase) : rotation+1
  arrow.style.setProperty("transform", `rotate(${rotation}deg`)
},20)
.arrow{
  --rotation: -90deg;
  margin: 5em;
  height: 160px;
  width: 150px;
  transform: rotate(var(--rotation));
  transform-origin: 68px 118px;  /* the position of the rotation point in the image */
}
<img src="https://i.imgur.com/crRJmHg.png" class="arrow">

Upvotes: 1

Stefan
Stefan

Reputation: 160

Animations like this are also possible through CSS. See this StackBlitz example.

Reference of tranfsorm https://www.w3schools.com/cssref/css3_pr_transform.asp

Upvotes: 1

Related Questions