如何在本机反应中创建旋转圆

时间:2018-10-05 09:39:41

标签: javascript react-native

我想在react native中创建一个旋转圆。我可以找到一个纯JavaScript来做到这一点:

https://codepen.io/adadsa/pen/QEzbak

但是我不知道如何在我的本机项目中使用此代码。

这是所有的javascript代码:

circle('layer-1');

            function circle(id) {

                var el = document.getElementById(id);

                var elDisplay = el.children[0];
                var elInteraction = el.children[1];

                var offsetRad = null;
                var targetRad = 0;
                var previousRad;


                try {
                    elInteraction.addEventListener('mousedown', down);
                }
                catch (err) {
                    console.log("Interaction not found");
                }

                function down(event) {
                    offsetRad = getRotation(event);
                    previousRad = offsetRad;
                    window.addEventListener('mousemove', move);
                    window.addEventListener('mouseup', up);
                }

                function move(event) {

                    var newRad = getRotation(event);
                    targetRad += (newRad - previousRad);
                    previousRad = newRad;
                    elDisplay.style.transform = 'rotate(' + (targetRad / Math.PI * 180) + 'deg)';
                }

                function up() {
                    window.removeEventListener('mousemove', move);
                    window.removeEventListener('mouseup', up);
                }

                function getRotation(event) {
                    var pos = mousePos(event, elInteraction);
                    var x = pos.x - elInteraction.clientWidth * .5;
                    var y = pos.y - elInteraction.clientHeight * .5;
                    return Math.atan2(y, x);
                }

                function mousePos(event, currentElement) {
                    var totalOffsetX = 0;
                    var totalOffsetY = 0;
                    var canvasX = 0;
                    var canvasY = 0;

                    do {
                        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
                        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
                    }
                    while (currentElement = currentElement.offsetParent)

                    canvasX = event.pageX - totalOffsetX;
                    canvasY = event.pageY - totalOffsetY;

                    return {
                        x: canvasX,
                        y: canvasY
                    };
                }
            }

是否可以在本地本机中使用此代码,或者我必须将其转换?

1 个答案:

答案 0 :(得分:0)

使用CSS可使组件旋转360度。您只需搜索即可在线获得CSS代码。请勿使用js进行操作 我为您找到了一个CSS代码here