Categories
CSS JavaScript JQuery

CSS/jQuery/JS Playing Cube

CSS Dice

Demo:

*to see the animation on the website click here.
*click and drag the cube and change its position.

To create a 3d playing cube you will need 6 pictures (one of each side of the cube). 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:100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.game {
  perspective: 800px;
}
.cube {
  font-size: 50px;
  width: 100px;
  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://lenadesignorg.files.wordpress.com/2020/04/1-1.png?w=100');}
.top {transform: rotateX(90deg) translateZ(1em);
       background-image:url('https://lenadesignorg.files.wordpress.com/2020/04/4-1.png?w=100');}

.right {transform: rotateY(90deg) translateZ(1em);
background-image:url('https://lenadesignorg.files.wordpress.com/2020/04/5-1.png?w=100');}

.left {transform: rotateY(-90deg) translateZ(1em);
background-image:url('https://lenadesignorg.files.wordpress.com/2020/04/2-1.png?w=100');}

.bottom {transform: rotateX(-90deg) translateZ(1em);
background-image:url('https://lenadesignorg.files.wordpress.com/2020/04/3-1.png?w=100');}

.back {transform: rotateY(-180deg) translateZ(1em);
background-image:url('https://lenadesignorg.files.wordpress.com/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)");
}

Enjoy coding!