Я хочу, чтобы объект вращался по кругу при нажатии кнопки вокруг определенного градуса. Как это исправить

Я хочу повернуть круг вокруг другого круга с определенной степенью при нажатии кнопки, но этого не происходит при нажатии кнопки, вот код с щелчком мыши. Пожалуйста, помогите мне, как я могу повернуть круг вокруг другого круга с помощью кнопки на определенный градус. Вот код Как сделать так, чтобы ротатор работал нормально.

<div id = "picker">
<div id = "picker-circle">
</div></div><img id = "image1" src = "Images/Homepage/apartment-architecture-ceiling-271724-min.jpg">`enter code here`<input type = "text" id = "circle_rot">

<script>
	var circle = document.getElementById('circle'),
		picker = document.getElementById('picker'),
		pickerCircle = picker.firstElementChild,
		rect = circle.getBoundingClientRect(),
		center = {
			x: rect.left + rect.width / 2,
			y: rect.top + rect.height / 2
		},

		transform = (function() {
			var prefs = ['t', 'WebkitT', 'MozT', 'msT', 'OT'],
				style = document.documentElement.style,
				p
			for (var i = 0, len = prefs.length; i < len; i++) {
				if ((p = prefs[i] + 'ransform') in style) return p
			}

			alert('your browser doesnot support css transforms!')
		})(),

		rotate = function(x, y) {
			var deltaX = x - center.x,
				deltaY = y - center.y,

				// The atan2 method returns a numeric value between -pi and pi representing the angle theta of an (x,y) point.
				// This is the counterclockwise angle, measured in radians, between the positive X axis, and the point (x,y).
				// Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.
				// atan2 is passed separate x and y arguments, and atan is passed the ratio of those two arguments.
				// * from Mozilla's MDN

				// Basically you give it an [y, x] difference of two points and it give you back an angle
				// The 0 point of the angle is left (the initial position of the picker is also left)

				angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI

			// Math.atan2(deltaY, deltaX) => [-PI +PI]
			// We must convert it to deg so...
			// / Math.PI => [-1 +1]
			// * 180 => [-180 +180]

			return angle
		},

		// DRAGSTART
		mousedown = function(event) {
			event.preventDefault()
			document.body.style.cursor = 'move'
			mousemove(event)
			document.addEventListener('mousemove', mousemove)
			document.addEventListener('mouseup', mouseup)
		},

		// DRAG
		mousemove = function(event) {
			picker.style[transform] = 'rotate(' + rotate(event.pageX, event.pageY) + 'deg)'
			//					alert(picker.style[transform]);
			$('#circle_rot').val(picker.style[transform]);

		},

		// DRAGEND
		mouseup = function() {
			document.body.style.cursor = null;
			document.removeEventListener('mouseup', mouseup)
			document.removeEventListener('mousemove', mousemove)
		}



	// DRAG START
	pickerCircle.addEventListener('mousedown', mousedown)

	// ENABLE STARTING THE DRAG IN THE BLACK CIRCLE
	circle.addEventListener('mousedown', function(event) {
		if (event.target == this) mousedown(event)

	})
</script>
<div id = "picker">
	<div id = "picker-circle">
	</div>
</div>
</div>
<img id = "image1" src = "Images/Homepage/apartment-architecture-ceiling-271724-min.jpg">
<input type = "text" id = "circle_rot">
enter code here

var circle = document.getElementById('circle'),
    picker = document.getElementById('picker'),
    pickerCircle = picker.firstElementChild,
    rect = circle.getBoundingClientRect(),
    center = {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2,
    },

    transform = (function() {
        var prefs = ['t', 'WebkitT', 'MozT', 'msT', 'OT'],
            style = document.documentElement.style,
            p
        for (var i = 0, len = prefs.length; i < len; i++) {
            if ((p = prefs[i] + 'ransform') in style) return p
        }

        alert('your browser doesnot support css transforms!')
    })(),

    rotate = function(x, y) {
        var deltaX = x - center.x,
            deltaY = y - center.y,

            // The atan2 method returns a numeric value between -pi and pi representing the angle theta of an (x,y) point.
            // This is the counterclockwise angle, measured in radians, between the positive X axis, and the point (x,y).
            // Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.
            // atan2 is passed separate x and y arguments, and atan is passed the ratio of those two arguments.
            // * from Mozilla's MDN

            // Basically you give it an [y, x] difference of two points and it give you back an angle
            // The 0 point of the angle is left (the initial position of the picker is also left)

            angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI

        // Math.atan2(deltaY, deltaX) => [-PI +PI]
        // We must convert it to deg so...
        // / Math.PI => [-1 +1]
        // * 180 => [-180 +180]

        return angle
    },

    // DRAGSTART
    mousedown = function(event) {
        event.preventDefault()
        document.body.style.cursor = 'move'
        mousemove(event)
        document.addEventListener('mousemove', mousemove)
        document.addEventListener('mouseup', mouseup)
    },

    // DRAG
    mousemove = function(event) {
        picker.style[transform] = 'rotate(' + rotate(event.pageX, event.pageY) + 'deg)'
        //                  alert(picker.style[transform]);
        $('#circle_rot').val(picker.style[transform]);

    },

    // DRAGEND
    mouseup = function() {
        document.body.style.cursor = null;
        document.removeEventListener('mouseup', mouseup)
        document.removeEventListener('mousemove', mousemove)
    }



// DRAG START
pickerCircle.addEventListener('mousedown', mousedown)

// ENABLE STARTING THE DRAG IN THE BLACK CIRCLE
circle.addEventListener('mousedown', function(event) {
    if (event.target == this) mousedown(event)

})

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
41
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Это то, что вы хотите?

var circle = document.getElementById('picker-circle'), //CHANGED
		picker = document.getElementById('picker'),
		rect = picker.getBoundingClientRect(), //CHANGED
    //REMOVED
		center = {
			x: rect.left + rect.width / 2,
			y: rect.top + rect.height / 2
		},

		transform = (function() {
			var prefs = ['t', 'WebkitT', 'MozT', 'msT', 'OT'],
				style = document.documentElement.style,
				p
			for (var i = 0, len = prefs.length; i < len; i++) {
				if ((p = prefs[i] + 'ransform') in style) return p
			}

			alert('your browser doesnot support css transforms!')
		})(),

		rotate = function(x, y) {
			var deltaX = center.x-x,
				deltaY = center.y-y,

				// The atan2 method returns a numeric value between -pi and pi representing the angle theta of an (x,y) point.
				// This is the counterclockwise angle, measured in radians, between the positive X axis, and the point (x,y).
				// Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.
				// atan2 is passed separate x and y arguments, and atan is passed the ratio of those two arguments.
				// * from Mozilla's MDN

				// Basically you give it an [y, x] difference of two points and it give you back an angle
				// The 0 point of the angle is left (the initial position of the picker is also left)

				angle = (Math.atan2(deltaY, deltaX) - Math.PI/4) * (180 / Math.PI) //CHANGED

			// Math.atan2(deltaY, deltaX) => [-PI +PI]
			// We must convert it to deg so...
			// / Math.PI => [-1 +1]
			// * 180 => [-180 +180]

			return angle
		},

		// DRAGSTART
		mousedown = function(event) {
			event.preventDefault()
			document.body.style.cursor = 'move'
			mousemove(event)
			document.addEventListener('mousemove', mousemove)
			document.addEventListener('mouseup', mouseup)
		},

		// DRAG
		mousemove = function(event) {
			picker.style[transform] = 'rotate(' + rotate(event.pageX, event.pageY) + 'deg)'
			//					alert(picker.style[transform]);
			$('#circle_rot').val(picker.style[transform]);

		},

		// DRAGEND
		mouseup = function() {
			document.body.style.cursor = null;
			document.removeEventListener('mouseup', mouseup)
			document.removeEventListener('mousemove', mousemove)
		}



	// DRAG START
	circle.addEventListener('mousedown', mousedown); //CHANGED

	// ENABLE STARTING THE DRAG IN THE BLACK CIRCLE
	circle.addEventListener('mousedown', function(event) {
		if (event.target == this) mousedown(event)

	})
#picker {
  border-radius: 50%;
  width:100px;
  height:100px;
  background:red;
}
#picker-circle {
  border-radius: 50%;
  width:20px;
  height:20px;
  background:blue;
  }
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "picker">
	<div id = "picker-circle">
	</div>
</div>

<img id = "image1" src = "Images/Homepage/apartment-architecture-ceiling-271724-min.jpg">
<input type = "text" id = "circle_rot">

НЕТ, это с мышью для портативных устройств. Я хочу, чтобы это было с сенсорными или мобильными устройствами. Как я могу использовать сенсорное событие с этим

Kanav Gilhotra 10.04.2019 06:00

Измените события мыши на события касания и получите местоположение события касания вместо события нажатия мыши.

Trobol 10.04.2019 15:38

Другие вопросы по теме