首页 > 解决方案 > JavaScript中使用数组的图像旋转

问题描述

我正在编写图像旋转功能。我创建了一个数组来存储变换函数的度数。

但是,我需要知道而不是递增数组,而是在数组之间移动下一个和上一个rotations

从左右切换不能按预期工作。

https://jsfiddle.net/andreas20/v94zLg8b/

rotations = ['90deg', '180deg', '270deg', '360deg']
let img = document.getElementById('img_blob');
let array_increment = 0

$('#left').click(() => {
  if (array_increment > 3)
    array_increment = 0

  img.style.transform = 'rotate(-' + rotations[array_increment] + ')'
  array_increment++
  console.log(array_increment)
})

$('#right').click(() => {
  if (array_increment > 3)
    array_increment = 0

  img.style.transform = 'rotate(' + rotations[array_increment] + ')'
  array_increment++
  console.log(array_increment)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="left">Left</button>
<button id="right">Right</button><br>

<img id="img_blob" src="https://i.imgur.com/vgD5ycf.jpg">

标签: javascriptjquery

解决方案


您可以在不使用数组的情况下进行类似的旋转

let img = document.getElementById('img_blob');
let rotationValue = 0;

$('#left').click(() => rotate(-1));
$('#right').click(() => rotate(1));

function rotate(direction) {
  rotationValue += 90 * direction;
  rotationValue = rotationValue % 360;
  img.style.transform = `rotate(${rotationValue}deg)`;
  // console.log(rotationValue);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="img_blob" src="https://dummyimage.com/150x150/000/fff" />
<button id="left">Left</button>
<button id="right">Right</button>


推荐阅读