gpt4 book ai didi

javascript - 旋转图像而不重置旋转

转载 作者:行者123 更新时间:2023-11-29 21:58:44 24 4
gpt4 key购买 nike

我有一个包含图像的页面。在拖动光标的同时单击并按住鼠标按钮可围绕其中心旋转图像。这是通过以下 JavaScript 代码(基于 this answer to a similar question )完成的:

$(function() {
var target = $('#david-hasselhoff'),
originX = target.offset().left + target.width() / 2,
originY = target.offset().top + target.height() / 2,
dragging = false;

target.mousedown(function(e) {
dragging = true;
});

$(document).mouseup(function() {
dragging = false
}).mousemove(function(e) {
var mouseX, mouseY, radians, degrees;

if (!dragging) {
return;
}

mouseX = e.pageX;
mouseY = e.pageY;
radians = Math.atan2(mouseY - originY, mouseX - originX),
degrees = radians * (180 / Math.PI);

target.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
target.css('-ms-transform', 'rotate(' + degrees + 'deg)');
target.css('transform', 'rotate(' + degrees + 'deg)');
});
});

这有两个问题:

1) 如果我旋转图像,松开鼠标按钮,然后再次旋转图像,旋转将被重置。我希望能够将它旋转一点,然后单击并拖动以再旋转一点。

2) 如果我单击图像的左侧并将其顺时针旋转几度,它会立即将旋转设置为 180 度(或更接近 -170 度)。我希望能够在拖动光标时旋转图像,而不管它从图像中心的哪一侧开始。

我希望这是有道理的。这是 fiddle :http://jsfiddle.net/C5QA9/

最佳答案

此处计算旋转的代码是获取图像垂直中心与光标当前位置之间的 Angular 。为了让点击时图片旋转顺畅,需要在旋转时减去这个 Angular 。此外,您需要跟踪上次拖动过程中旋转的位置,并将此 Angular 添加到当前旋转:

$(function() {
var target = $('#david-hasselhoff'),
originX = target.offset().left + target.width() / 2,
originY = target.offset().top + target.height() / 2,
dragging = false,
startingDegrees = 0,
lastDegrees = 0,
currentDegrees = 0;

target.mousedown(function(e) {
dragging = true;
mouseX = e.pageX;
mouseY = e.pageY;
radians = Math.atan2(mouseY - originY, mouseX - originX),
startingDegrees = radians * (180 / Math.PI);
});

$(document).mouseup(function() {
lastDegrees = currentDegrees;
dragging = false;
}).mousemove(function(e) {
var mouseX, mouseY, radians, degrees;

if (!dragging) {
return;
}

mouseX = e.pageX;
mouseY = e.pageY;
radians = Math.atan2(mouseY - originY, mouseX - originX),
degrees = radians * (180 / Math.PI) - startingDegrees + lastDegrees;

currentDegrees = degrees;

target.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
target.css('-ms-transform', 'rotate(' + degrees + 'deg)');
target.css('transform', 'rotate(' + degrees + 'deg)');
});
});

这是 fiddle :http://jsfiddle.net/C5QA9/1/

关于javascript - 旋转图像而不重置旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25046630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com