Select Page

Rotate elements using Javascript

We will be using the Propeller Javascript library to rotate elements. It supports inertia and stepwise rotation and is also compatible with touch devices. To rotate element you can simply drag or swipe.

We will be making this:

Let’s start with HTML:

<div class="webisora-demo">
        <p id="instructions"></p>
        <div id="container">
            <img id="rotate-this" src="https://webisora.com/wp-content/uploads/2018/07/paper-min.png" alt="" />
        </div>
</div>
<script src="https://webisora.com/assets/js/propeller.min.js"></script>

The p with id="instructions" is empty for now. We will populate the instruction, either “SWIPE TO ROTATE” for touch-enabled devices or “USE MOUSE TO DRAG AND ROTATE” for desktop or devices that does not support touch, using javascript.

Now, let’s add some CSS:

.webisora-demo {
    max-width: 350px;
    max-height: 400px;
 }

#background {
    width: 300px;
    margin: 8%;
}

#instructions {
    padding: 5px;
    text-align: center;
    font-weight: bold;
}

Finally, JS:

startRotation();
function startRotation() {

	if (is_touch_device()) {
		document.getElementById("instructions").innerHTML = "SWIPE TO ROTATE";
	}
	else {
		document.getElementById("instructions").innerHTML = "USE MOUSE TO DRAG AND ROTATE";
	}

	var rotateElement = document.getElementById('rotate-this');
	new Propeller(rotateElement , {
		inertia: 0.99, speed: 10,
	});

}

function is_touch_device() {
	var prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
	var mq = function (query) {
		return window.matchMedia(query).matches;
	}

	if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
		return true;
	}
	var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('');
	return mq(query);
}

In the above Javascript code, function is_touch_device is used to check whether the device supports touch or not and add the instructions accordingly. Then we pass our rotation element to the Propeller. We are using inertia as 0.99 so that the rotation will stop after a certain duration. If you do not want to stop then simply put inertia as 1. Here is the list of other options you can use for this library:

  • angle sets initial angle
  • inertia is the most valueble option. It is a number between 0 and 1. 0 means no rotation after mouse was released. 1 means infinite rotation. For this demo we use inertia equals to 0.99.
  • speed – initial speed of rotation. It also can be used as property in runtime.
    minimalSpeed – minimal speed of rotation. Works only if propeller have inertia between 0 and 1.
  • step allows to set step in degrees for stepwise mode.
  • stepTransitionTime enables CSS transition to move from step to step. This makes steps smooth and allows to use CSS transitions easing.
  • stepTransitionEasing CSS easing mode for transition when in stepwise mode and stepTransitionTime is more than zero. A bit more about easing functions
    onRotate callback executed when rotated. You can easily get current angle as this.angle inside of callback function.
  • onStop callback executed when stopped.
  • onDragStart callback executed when start dragging.
  • onDragStop callback executed when stop dragging.

You can check this project in the codepen as well.

To see all the demos of Propeller click here.

2 Comments

  1. Fritz

    Hi
    Thank you for the code. I find it most useful.

    I am developing a tangram game. I have completed the drag and drop, but I need to rotate each one of the seven shapes.

    I intend placing an event listener, that will trigger the code on each Tangram element. I have tried the following change:

    var rotateElement = document.getElementById(tangramShape) instead of var rotateElement = document.getElementById(“rotate-this”). I have created a variable called var tangramShape = “‘rotate-this'”;

    This does not work. Would you have any advice?

    My current code for the tangram game is:

    #div1 {
    z-index = 1;
    position:fixed;
    background-image: url(“tangramFox.png”);
    background-repeat: no-repeat;
    //background-size: contain, cover;
    background-size: cover;
    margin-left: 200px;
    width: 450px;
    height: 350px;
    border-style: solid;
    }

    #drag1{
    z-index = 2;
    position:absolute;
    width: 75px;
    height:75px;
    float:left;
    left: 0px;
    top: 0px;

    }

    #drag2{
    z-index = 3;
    position:absolute;
    float:left
    width: 75px;
    height:75px;
    left: 0px;
    top: 0px;
    }

    #redTriangle{
    z-index = 4;
    position:elative
    width:50px;
    height:50px;
    }

    demo

    var tangramShape;
    var disableDrag;

    document.getElementById(“drag1”).addEventListener(“mouseover”, blueParalell);
    document.getElementById(“drag2”).addEventListener(“mouseover”, yellowParalell);

    function blueParalell(){
    document.getElementById(“drag1”).draggable = true;
    tangramShape = document.getElementById(“drag1”);
    disableDrag = document.getElementById(“drag1”);
    //alert(“disable drag 1” + disableDrag.id);
    }

    function yellowParalell(){
    document.getElementById(“drag2”).draggable = true;
    tangramShape = document.getElementById(“drag2”);
    disableDrag = document.getElementById(“drag2”);
    //alert(“disable drag 2” + disableDrag.id);
    }

    function allowDrop(ev) {
    ev.preventDefault();
    }

    function drag(ev) {
    ev.dataTransfer.setData(“text”, ev.target.id);
    tangramShape = ev.currentTarget.id;
    //alert( “drag current..” + tangramShape);
    }

    function drop(ev) {
    alert(“Currentid” + event.currentTarget.id);
    ev.preventDefault();
    var data = ev.dataTransfer.getData(“text”);
    //ev.target.appendChild(document.getElementById(data));

    z = event.offsetX;
    a = event.offsetY;
    var x = event.clientX; // Get the horizontal coordinate
    var y = event.clientY; // Get the vertical coordinate
    //alert(“place” + tangramShape);

    //var zz = 57;
    //var zzz= z-zz;

    //var aa = 80;
    //var aaa = aa-80;

    document.getElementById(tangramShape).style.marginLeft = z;
    document.getElementById(tangramShape).style.marginTop = a;

    //if ( event.target.tangramShape !== “IMG” ) {
    //event.target.appendChild(document.getElementById(data));
    //}

    }

    function dragLeave(event) {
    if ( event.target.id = tangramShape) {
    document.getElementById(“demo”).innerHTML = “Left the dropzone”;
    //event.target.style.border = “”;
    //event.target.style.visibility = “hidden”;
    //ev.stopPropagation();
    // return false;

    }
    }

    Your assistance will be most appreciated.

    Reply
    • sagar

      Hey Fritz,

      I would love to help. But I cannot see your demo link. Can you please send jsfiddle or codesandbox link?

      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *