[英]Image rotation in JavaScript using array
我正在編寫圖像旋轉功能。 我創建了一個數組來存儲變換函數的度數。
但是我需要知道而不是增量數組,在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">
你可以在不使用數組的情況下進行類似的旋轉
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>
你對旋轉中的減號有誤解
-90deg, -180deg, -270deg, -360deg
與90deg, 180deg, 270deg, 360deg
向后不同(即0deg, -90deg, -180deg, -270deg
,所以偏移量為 1)
我所做的是,我從零開始並在數組內前后移動
rotations = ['0deg', '45deg', '90deg', '135deg', '180deg', '225deg', '270deg', '315deg'] let img = document.getElementById('img_blob'); let array_increment = 0 array_increment = 0; $('#left').click(() => { array_increment-- array_increment = (array_increment + rotations.length) % rotations.length console.log(array_increment) img.style.transform = 'rotate(' + rotations[array_increment] + ')' }) $('#right').click(() => { array_increment++ array_increment = (array_increment + rotations.length) % rotations.length console.log(array_increment) img.style.transform = 'rotate(' + rotations[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.picsum.photos/id/190/300/300.jpg">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.