Categories
CSS JavaScript JQuery

CSS/jQuery/JS Playing Cube

Let’s take a closer look on another example of the tutorial CSS Perspective Property, CSS Perspective-orgin Property & 3d Cube and let’s create a 3d Playing Cube.

CSS Playing Cube

Click and drag the cube and change its the position!

*animation opened in the Safari browser.
To see the live output of the animation click here.

To create a 3d playing cube you will need 6 pictures. You can use these below:

and then:

  1. Add HTML
  2. Add CSS
  3. Add jQuery/JavaScript

Step1.

Add HTML

<div class="game">
  <div class="cube">
  <div class="side front"></div>
  <div class="side back"></div>
  <div class="side right"></div>
  <div class="side left"></div>
  <div class="side top"></div>
  <div class="side bottom"></div>
  </div>
</div>

Step2.

Add CSS

body {
  height:80vh;
  background: linear-gradient(6deg, rgba(131,58,180,1) 0%, rgba(253,29,29,1) 50%, rgba(252,176,69,1) 100%);
}

.game {
  perspective: 800px;
}
.cube {
  font-size: 50px;
  width: 100px;
  margin: 4.5em auto;
  transform-style: preserve-3d;
  transform: rotateX(-45deg) rotateY(30deg);
}

.side {
  position: absolute;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  text-align: center;
  line-height: 2em;
}

.front {transform: translateZ(1em);
        background-image:url('https://lenadesign.org/wp-content/uploads/2020/04/1-1.png?w=100');}
.top {transform: rotateX(90deg) translateZ(1em);
       background-image:url('https://lenadesign.org/wp-content/uploads/2020/04/4-1.png?w=100');}

.right {transform: rotateY(90deg) translateZ(1em);
background-image:url('https://lenadesign.org/wp-content/uploads/2020/04/5-1.png?w=100');}

.left {transform: rotateY(-90deg) translateZ(1em);
background-image:url('https://lenadesign.org/wp-content/uploads/2020/04/2-1.png?w=100');}

.bottom {transform: rotateX(-90deg) translateZ(1em);
background-image:url('https://lenadesign.org/wp-content/uploads/2020/04/3-1.png?w=100');}

.back {transform: rotateY(-180deg) translateZ(1em);
background-image:url('https://lenadesign.org/wp-content/uploads/2020/04/6-1.png?w=100');}

Step3.

Add jQuery/JavaScript

var lastMouseX = 0,
	lastMouseY = 0;
var rotX = 0,
	rotY = 0;

$(document).on("mousedown", function(ev) {
	lastMouseX = ev.clientX;
	lastMouseY = ev.clientY;
	$(document).on("mousemove", mouseMoved);
});
$(document).on("mouseup", function() {
	$(document).off("mousemove", mouseMoved);
});

function mouseMoved(ev) {
	var deltaX = ev.pageX - lastMouseX;
	var deltaY = ev.pageY - lastMouseY;

	lastMouseX = ev.pageX;
	lastMouseY = ev.pageY;

	rotY -= deltaX * 0.1;
	rotX += deltaY * 0.1;

	$(".cube").css("transform", "translateX( 0px) rotateX( " + rotX + "deg) rotateY(" + rotY + "deg)");
}

To see the live output go to lenastanley.com.

Enjoy coding!

Leave a Reply