Reposition texture in three.js - javascript

I have drawn a texture in three.js. However, I would like to reposition (change angle) of the texture a bit. Please see images below. My required output is basically the current output tilted a bit down such that the green surface is parallel to the ground, and I can see more of the sky.
I have tried playing around with the camera settings, and also the position and rotation of the texture. However, I haven't been able to get the required output.
Original output
Required
Here is my code on jsbin
Code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tennis</title>
<link rel="stylesheet" type="text/css" href="../css/home.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!--adding the js libraries-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r72/three.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/3587259/Code/Threejs/OrbitControls.js"></script><!--to be able to pan and do controls.update-->
</head>
<body>
<div id="ThreeJS"></div>
</body>
<script>
var animationTracker,count=0;
var floormesh=null,floorTexture,floorMaterial,floorGeometry;//floor
var skyBoxGeometry,skyBoxMaterial,skyBox;//sky
var SCREEN_WIDTH,SCREEN_HEIGHT,scene,camera,renderer,light,container,animationTracker;
var mesh;
var textAnimationCount = 0,textMesh;
init();
function init()
{
/* 1.set SCREEN_WIDTH and SCREEN_HEIGHT */
SCREEN_WIDTH = window.innerWidth-110, SCREEN_HEIGHT = window.innerHeight;
console.log(window.innerWidth);
console.log(window.innerHeight);
/* 2.scene*/
scene = new THREE.Scene();
/* 3.camera */
camera = new THREE.PerspectiveCamera(45,SCREEN_WIDTH/SCREEN_HEIGHT,0.1,1000);
camera.position.x = 0;
camera.position.y = 14;
camera.position.z = 45;
camera.lookAt(scene.position);
/* 4.renderer */
renderer = new THREE.WebGLRenderer();
renderer.setSize(SCREEN_WIDTH,SCREEN_HEIGHT)
/* 7.light */
light = new THREE.DirectionalLight('white',1);
//light.position.set(0,10,10).normalize();
light.position.set(20,20,0).normalize();
/* adding elements to scene */
drawFloorAndSky();
/* 8.weave together */
container = document.getElementById('ThreeJS')
container.appendChild(renderer.domElement);
//scene.add(cube);
renderer.render(scene,camera);
}
function drawFloorAndSkyAnimate()
{
animationTracker = requestAnimationFrame( drawFloorAndSkyAnimate );
count++;
renderer.render(scene,camera);
controls.update();
console.log("position : x=="+floor.position.x+",y=="+floor.position.y+",z=="+floor.position.z);
console.log("rotation : x=="+floor.rotation.x+",y=="+floor.rotation.y+",z=="+floor.rotation.z);
}
function drawFloorAndSky()
{
//////////////
// CONTROLS //
//////////////
// move mouse and: left click to rotate,
// middle click to zoom,
// right click to pan
controls = new THREE.OrbitControls( camera, renderer.domElement );
///////////
// FLOOR //
///////////
// note: 4x4 checkboard pattern scaled so that each square is 25 by 25 pixels.
//var floorTexture = new THREE.ImageUtils.loadTexture( 'images/checkerboard.jpg' );
floorTexture = new THREE.ImageUtils.loadTexture( '../images/grass256.jpg' );
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 20, 20 );
// DoubleSide: render texture on both sides of mesh
floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
floorGeometry = new THREE.PlaneGeometry(100, 100, 1, 1);
floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.position.y = -0.5;
floor.rotation.x = Math.PI / 2;
scene.add(floor);
/////////
// SKY //
/////////
// recommend either a skybox or fog effect (can't use both at the same time)
// without one of these, the scene's background color is determined by webpage background
// make sure the camera's "far" value is large enough so that it will render the skyBox!
skyBoxGeometry = new THREE.CubeGeometry( 1000, 1000, 1000 );
// BackSide: render faces from inside of the cube, instead of from outside (default).
skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0x9999ff, side: THREE.BackSide } );
skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
scene.add(skyBox);
/* keeping it going */
requestAnimationFrame( drawFloorAndSkyAnimate );
renderer.render(scene,camera);
controls.update();
}
</script>
</html>
CSS
html, body {
height: 100%;
width: 100%;
}
a, a:visited, a:focus, a:hover {
color: #0A5C2F !important;
text-decoration: none !important;
}
svg a, svg a:visited, svg a:focus, svg a:hover {
color: #0A5C2F;
text-decoration: none;
}
.row {
margin-left: 0 !important;
margin-right: 0 !important;
}
.button {
font-size: 1.4rem;
line-height: 2rem;
}
.button:hover, .button.active:hover {
opacity: 0.5;
cursor: pointer;
}
/* top bar */
#title, #bottom {
/*float:left;*/
height: 5%;
text-align: center;
display: table;
table-layout: fixed;
margin: 0;
width: 100%;
}
#title a:hover {
opacity: 0.5;
}
#prev, #next {
display: table-cell;
vertical-align: middle;
width: 30%;
font-size: 1.5rem;
color: #0A5C2F;
}
/* main */
#main {
height: 90%;
max-height: 90%;
max-width: 100%;
overflow: hidden;
}
#main text {
font-size: 1rem;
text-anchor: middle;
}wwq
#main circle:hover {
cursor: pointer;
}
/* options */
#options {
height: 10%;
text-align: center;
display: table;
table-layout: fixed;
margin: 0;
width: 100%;
}
#options-1-table, #options-2-table {
display: table;
height: 100%;
width: 100%;
}
#options-1, #options-2 {
text-align: center;
display: table-cell;
vertical-align: middle;
height: 100%;
width: 35%;
}
/* chart */
#chart-row {
height: 90%;
}
#chart {
height: 100%;
text-align: center;
padding-left: 0;
padding-right: 0;
}
#chart-title {
text-align: center;
display: table-cell;
vertical-align: middle;
height: 100%;
width: 30%;
font-size: 1.4rem;
background-color: #0A5C2F;
color: #ffffff;
}
#ThreeJS
{
z-index: 1; position: absolute; left:0px; top:190px;
/*width:100%;*/
width: 1320px;
padding: 10px;
border: 5px solid navy;
margin: 10px;
}
/*ThreeJS*/
/*#ThreeJS*/
/*{*/
/*z-index: 1; position: absolute; left:0px; top:190px;*/
/*!*width:100%;*!*/
/*width: 1300px;*/
/*padding: 25px;*/
/*border: 5px #0A5C2F;*/
/*margin: 10px;*/
/*}*/
Image used link : https://www.dropbox.com/s/ot28m991wvacfla/grass256.jpg?dl=0

What you may want to do is to set a target to your controls, which is per default set to (0, 0, 0). You get the desired perspective by increasing the y-value:
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.target.set( 0, 10, 0 );

Related

HTML5 Canvas rectangles click coordinates is inconsistent

I made a canvas size as A4, i draw a rectangles inside and when i click the light blue rectangle it will call a function but the coordinates of the click on the rectangle is inconsistent and every row the y level is needed to click more lower then the light blue rectangle.
How i make the coordinates more accurate?
(Code need full screen)
'use strict';
function mmTopx(mm) {
//return mm * 3.7795275591;
//return mm * 3.7795275590551;
return (mm * 96) / 25.4;
}
function cmTopx(cm) {
return cm * 1; /* NEED TO FIX */
}
// Get mouse position
function getMousePos(c, evt) {
var rect = c.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top,
};
}
class sticker {
#width;
#height;
#fullheight;
constructor(width = 1, height = 1, fullheight = 1) {
if (!sticker.isNumber(width) || !sticker.isNumber(height) || !sticker.isNumber(fullheight)) throw 'Only accept number';
this.#width = width;
this.#height = height;
this.#fullheight = fullheight;
}
static isNumber(n) {
return !isNaN(parseFloat(n)) && !isNaN(n - 0) && typeof n != 'string';
}
get size() {
return { width: this.#width, height: this.#height, fullheight: this.#fullheight };
}
get width() {
return this.#width;
}
get height() {
return this.#height;
}
get fullheight() {
return this.#fullheight;
}
set width(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#width = n;
}
set height(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#height = n;
}
set fullheight(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#fullheight = n;
}
}
window.onload = () => {
const controls = document.querySelectorAll('.control');
const canvas = document.querySelector('.A4');
const canvasPadding = {
left:
window
.getComputedStyle(canvas, null)
.getPropertyValue('padding-left')
.match(/\d+.\d+|\d+/)[0] - 0,
top:
window
.getComputedStyle(canvas, null)
.getPropertyValue('padding-top')
.match(/\d+.\d+|\d+/)[0] - 0,
};
/* ///////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////// */
/* ///// CANVAS ///// */
/* ///////////////////////////////////////////////////// */
/* canvas */
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext('2d');
const _sticker = new sticker(mmTopx(25), mmTopx(12), mmTopx(37));
let Stickers = [];
const drawSticker = (x, y, width, height, fullheight) => {
Stickers.push({
color: '#d8d8d8',
width: width,
height: height,
x: x,
y: y,
clicked: function () {
console.log(`you clicked me, ${this.x} ${this.y}`);
},
});
/* full area */
ctx.fillStyle = '#e8f2f8';
ctx.fillRect(x, y, width, fullheight); // x y width height
/* print area */
ctx.fillStyle = '#d8d8d8';
ctx.fillRect(x, y, width, height, fullheight); // x y width height
};
const render = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Stickers = [];
const size = _sticker.size;
for (let y = 0; y < canvas.height - size.fullheight; y += size.fullheight + 10) {
for (let x = 10; x < canvas.width - size.width; x += size.width + 1) {
drawSticker(x, y, size.width, size.height, size.fullheight);
}
}
};
/* ///////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////// */
/* ///// Event Listeners ///// */
/* ///////////////////////////////////////////////////// */
canvas.addEventListener('updateRender', (event) => {
const lengthType = event.detail.dimensionValue.match(/mm|cm/)[0];
let value = event.detail.dimensionValue.match(/\d+/)[0] - 0;
switch (lengthType) {
case 'cm':
//value = cmTopx(value);
break;
case 'mm':
default:
value = mmTopx(value);
break;
}
/* Set the new sticker size */
switch (event.detail.dimension) {
case 'width':
_sticker.width = value;
break;
case 'height':
_sticker.height = value;
break;
case 'fullheight':
_sticker.fullheight = value;
break;
}
render();
});
const event = new Event('change');
controls.forEach((_control) => {
_control.addEventListener(
'change',
(event) => {
const value = event.target.value;
const name = event.target.name;
const dimension = event.target.getAttribute('data-sticker-dim');
const detail = {};
detail['dimension'] = dimension;
detail['dimensionValue'] = value;
detail['name'] = name;
const updateSticker = new CustomEvent('updateRender', { detail: detail });
canvas.dispatchEvent(updateSticker);
},
true
);
const input = _control.querySelector('input');
input.dispatchEvent(event);
});
/* click event for text input */
canvas.addEventListener('click', function (e) {
e.preventDefault();
let x = parseInt(e.clientX - canvas.offsetLeft - canvasPadding.left);
let y = parseInt(e.clientY - canvas.offsetTop - canvasPadding.top);
if (x >= 0 && y >= 0) {
for (let index = 0; index < Stickers.length; index++) {
const _sticker = Stickers[index];
if (
x >= _sticker.x &&
x <= Math.floor(_sticker.x + _sticker.width) &&
y >= _sticker.y &&
y <= Math.floor(_sticker.y + _sticker.height)
) {
_sticker.clicked();
break;
}
}
}
});
/* ///////////////////////////////////////////////////// */
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
background-color: #fafafa;
}
/* //////////////////////////////////////////////////////////// */
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-self: flex-start;
overflow: auto;
}
/* //////////////////////////////////////////////////////////// */
.container .controllers {
position: sticky;
top: 50%;
transform: translateY(-50%);
width: 250px;
height: 500px;
flex: 0 0 100px;
border-radius: 20px;
box-sizing: border-box;
padding: 20px;
margin-left: 5px;
border: 1px solid #9e9e9e;
}
.container .controllers .control {
position: relative;
flex: 0 0 100%;
height: 50px;
padding: 5px;
}
.container .controllers .control:first-child {
margin-top: 5px;
}
.container .controllers .control:not(:first-child) {
margin-top: 20px;
}
.container .controllers .control label::before {
content: attr(data-placeholder);
position: absolute;
left: 20px;
top: 20px;
color: #65657b;
font-family: sans-serif;
line-height: 14px;
pointer-events: none;
transform-origin: 0 50%;
transition: transform 200ms, color 200ms;
}
.container .controllers .control .cut {
position: absolute;
border-radius: 10px;
height: 20px;
width: fit-content;
left: 20px;
top: -20px;
transform: translateY(0);
transition: transform 200ms;
}
.container .controllers .control input {
height: 100%;
padding: 4px 20px 0;
width: 100%;
background-color: #eeeeee;
border-radius: 12px;
border: 0;
outline: 0;
box-sizing: border-box;
color: #eee;
font-size: 18px;
color: black;
}
.container .controllers .control input:focus ~ .cut,
.container .controllers .control input:not(:placeholder-shown) ~ .cut {
transform: translateY(8px);
}
.container .controllers .control input:focus ~ label::before,
.container .controllers .control input:not(:placeholder-shown) ~ label::before {
content: attr(data-focus-placeholder);
transform: translateY(-30px) translateX(10px) scale(0.75);
}
.container .controllers .control input:not(:placeholder-shown) ~ label::before {
content: attr(data-focus-placeholder);
color: #808097;
}
.container .controllers .control input:focus ~ label::before {
color: #dc2f55;
}
/* //////////////////////////////////////////////////////////// */
.container textarea {
background: none;
outline: none;
}
.container .A4 {
align-self: center;
width: 21cm;
flex: 0 0 29.7cm;
padding: 1cm;
border: 1px #d3d3d3 solid;
border-radius: 5px;
background: #f5f5f5;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
/* //////////////////////////////////////////////////////////// */
#page {
size: A4;
margin: 0;
}
#media print {
html,
body {
height: 99%;
}
.page {
margin: 0;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>A4 Render Stickers</title>
</head>
<body>
<div class="container">
<div class="controllers">
<button>print</button>
<div class="control">
<input type="text" value="25mm" data-sticker-dim="width" name="printWidth" placeholder=" " />
<div class="cut"></div>
<label for="printWidth" data-focus-placeholder="Width print" data-placeholder="Width size of print area"></label>
</div>
<div class="control">
<input type="text" value="12mm" data-sticker-dim="height" name="printHeight" placeholder=" " />
<div class="cut"></div>
<label for="printHeight" data-focus-placeholder="Height print" data-placeholder="Height size of print area"></label>
</div>
<div class="control">
<input type="text" value="37mm" data-sticker-dim="fullheight" name="stikcerHeight" placeholder=" " />
<div class="cut"></div>
<label for="stikcerHeight" data-focus-placeholder="Full height sticker" data-placeholder="Height size of full sticker"></label>
</div>
</div>
<canvas width="800" height="800" class="A4"></canvas>
</div>
</body>
</html>

Three.js freezes CSS animated background images and transitions

I've run into issue with Three.js (WebGL) - it freezes background animations (.gif in my case) and CSS transitions? Bascially when i don't trigger any CSS transition, the background GIF seems to freeze... but when I do trigger CSS transition (literally any), everything seems to move/animate/transition like it should. First time seeing this, so I would appreciate any help on debugging this and explaining me why does it act that way!? Should i set up some kind of delta time for animate()?
Here is my code example (try hovering menu, to see the issue with bg):
/**
* Hero Canvas
*/
var heroCanvasWrap = document.getElementById('hero-canvas');
THREE.Cache.enabled = true;
let container;
let camera, scene, renderer;
let group, textMesh1, textGeo, materials;
let text = "three.js",
bevelEnabled = true,
font = undefined;
const height = 20,
size = 70,
curveSegments = 4,
bevelThickness = 2,
bevelSize = 1.5;
const fontMap = {
"helvetiker": 0,
"optimer": 1,
"gentilis": 2,
"droid/droid_sans": 3,
"droid/droid_serif": 4
};
const weightMap = {
"regular": 0,
"bold": 1
};
const reverseFontMap = [];
const reverseWeightMap = [];
for ( const i in fontMap ) reverseFontMap[ fontMap[ i ] ] = i;
for ( const i in weightMap ) reverseWeightMap[ weightMap[ i ] ] = i;
let targetRotation = 0;
let targetRotationOnPointerDown = 0;
let pointerX = 0;
let pointerXOnPointerDown = 0;
let windowHalfX = window.innerWidth / 2;
let fontIndex = 1;
init();
animate();
function decimalToHex( d ) {
let hex = Number( d ).toString( 16 );
hex = "000000".substr( 0, 6 - hex.length ) + hex;
return hex.toUpperCase();
}
function init() {
container = document.createElement( 'div' );
heroCanvasWrap.appendChild( container );
// CAMERA
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1500 );
camera.position.set( 0, 100, 500 );
// cameraTarget = new THREE.Vector3( 0, 150, 0 );
// SCENE
scene = new THREE.Scene();
// LIGHTS
const dirLight = new THREE.DirectionalLight( 0xffffff, 0.75 );
dirLight.position.set( 0, 0, 70 ).normalize();
scene.add( dirLight );
// Get text from hash
materials = [
new THREE.MeshPhongMaterial( { color: 0xE1885D } )
];
group = new THREE.Group();
group.position.y = 100;
scene.add( group );
const loader = new THREE.FontLoader();
loader.load( 'http://localhost:1234/montserrat-bold.json', function ( response ) {
font = response;
refreshText();
} );
// RENDERER
renderer = new THREE.WebGLRenderer( { alpha:true, antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
// EVENTS
container.style.touchAction = 'none';
}
function createText() {
textGeo = new THREE.TextGeometry( text, {
font: font,
size: size,
height: height,
curveSegments: curveSegments,
bevelThickness: bevelThickness,
bevelSize: bevelSize,
bevelEnabled: bevelEnabled
} );
textGeo.computeBoundingBox();
const centerOffset = - 0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x );
textMesh1 = new THREE.Mesh( textGeo, materials );
textMesh1.position.x = centerOffset;
group.add( textMesh1 );
}
function refreshText() {
group.remove( textMesh1 );
if ( ! text ) return;
createText();
}
//
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
group.rotation.y += ( targetRotation - group.rotation.y ) * 0.05;
// camera.lookAt( cameraTarget );
renderer.clear();
renderer.render( scene, camera );
}
/**
* Document is ready?
* #param {*} callbackFunc
*/
function ready(callbackFunc) {
if (document.readyState !== 'loading') {
// Document is already ready, call the callback directly
callbackFunc();
} else if (document.addEventListener) {
// All modern browsers to register DOMContentLoaded
document.addEventListener('DOMContentLoaded', callbackFunc);
} else {
// Old IE browsers
document.attachEvent('onreadystatechange', function() {
if (document.readyState === 'complete') {
callbackFunc();
}
});
}
}
/**
* Document is redy! Init js...
*/
ready(function() {
/**
* Toggle light/dark mode
*/
var lightToggle = document.querySelector('.light-toggle'),
theBody = document.body;
lightToggle.onclick = function() {
theBody.classList.toggle('dark');
}
/**
* Toggle main menu
*/
var toggleMenu = document.querySelector('.toggle-menu'),
toggleMenuContent = document.getElementById('toggle-menu-content'),
headerHead = document.querySelector('header.head');
toggleMenu.onclick = function() {
/* theBody.classList.toggle('overflow-hidden'); */
headerHead.classList.toggle('fixed');
toggleMenuContent.classList.toggle('open');
}
});
/** Tailwind **/
#import 'https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.0.3/tailwind.min.css';
/** Montserrat Font **/
#import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
/**
* MAIN
**/
body {
width: 100%;
height: 100%;
font-family: "Montserrat", sans-serif;
overflow-x: hidden;
color: #000000;
background-color: #ffffff;
background-image: url("https://i.ibb.co/mGVpddB/bg.gif");
background-repeat: repeat;
}
a:focus,
button:focus{
outline: none !important; /** Remove all link & button outlines **/
}
/** Fullscreen helper **/
.fullscreen-bg {
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
/* background-attachment: fixed; */
}
.btn {
position: relative;
color: #000000;
font-size: 20px;
font-weight: 900;
font-style: italic;
text-transform: lowercase;
z-index: 10;
}
.btn.btn-slash::before{
display: block;
content: "";
position: absolute;
top: 50%;
left: 10%;
transform: translateY(-50%) skewX(25deg);
background: #DBDBDB;
width: 10px;
height: 45px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.btn.btn-slash:hover::before{
width: 80%;
}
/* HERO */
.light-toggle {
position: relative;
display: block;
width: 30.422px;
height: 31.898px;
z-index: 300;
}
.light-toggle::before,
.light-toggle::after {
content: "";
display: block;
position: absolute;
width: 30.422px;
height: 31.898px;
top: 50%;
margin-top: -15.949px;
}
.light-toggle::before {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='30.422' height='31.898' viewBox='0 0 30.422 31.898'%3E%3Cpath class='a' d='M11.576,54A15.415,15.415,0,0,1,1.269,50.192a12.031,12.031,0,0,1,0-18.385A15.415,15.415,0,0,1,11.576,28a16.274,16.274,0,0,1,3.924.477,14.859,14.859,0,0,0-7.63,4.6,11.906,11.906,0,0,0,0,15.853,14.86,14.86,0,0,0,7.63,4.6A16.273,16.273,0,0,1,11.576,54Z' transform='matrix(0.799, -0.602, 0.602, 0.799, -14.455, -13.034)' style='fill:gray;'/%3E%3C/svg%3E%0A");
}
#toggle-menu-content {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 0;
overflow: hidden;
}
#toggle-menu-content.open {
height: 100% !important;
}
#toggle-menu-content footer .light-toggle{
margin-top: 35px;
}
header.head {
position: absolute;
}
header.head.fixed {
z-index: 300;
}
.menu-links li {
margin-bottom: 30px;
}
.menu-links li a {
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.menu-links li a {
font-size: 30px;
font-weight: 600;
}
.menu-links li a:hover {
margin-left: -25px;
padding-right: 25px;
}
.menu-links li.active {
margin-left: -80px !important;
}
.menu-links li.active a:hover {
margin-left: 0 !important;
padding-right: 0 !important;
}
.menu-links li.active a {
color: #E1885D;
font-weight: 800;
font-style: italic;
}
.menu-links li.active a::before {
display: inline-block;
content: "šŸ‘‰";
float: left;
margin-right: 10px;
}
/** Footer **/
footer address a {
font-style: normal !important;
font-weight: 500;
font-size: 18px;
}
.socials li {
margin-bottom: 10px;
}
.socials li a {
display: block;
font-weight: 700;
font-size: 18px;
color: #808080;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
transform: rotate(-90deg);
}
.socials li a .dot {
color: #FA1DA5;
}
/**
* MAIN / DARK
**/
body.dark {
color: #ffffff !important;
background-color: #000000 !important;
background-image: url("../img/dark-bg.gif") !important;
}
.dark .btn.btn-slash {
color: #ffffff;
}
.dark .btn.btn-slash::before {
background: #4D4D4D;
}
.dark .footer-logo path,
.dark .footer-logo rect {
fill: #ffffff;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.0.3/tailwind.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r125/three.min.js"></script>
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EC</title>
<meta name="description" content="" />
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<nav id="toggle-menu-content">
<header class="p-36">
<ul class="menu-links">
<li class="active">īsumā</li>
<li>pratība</li>
<li>paveiktais</li>
<li>klienti & draugi</li>
</ul>
</header>
<footer class="pl-36 pr-12 py-20 grid grid-cols-6 gap-x-24">
<div class="col-span-3"></div>
<div class="relative col-start-5 col-end-7">
<div class="absolute bottom-0 right-0">
<ul class="socials relative inline float-right">
<li>ig<span class="dot">.</span></li>
<li>fb<span class="dot">.</span></li>
</ul>
<button class="light-toggle mr-12"></button>
</div>
</div>
</footer>
</nav>
<header id="hero" class="relative w-full h-full">
<header class="head top-0 left-0 w-full p-12 z-20">
<nav class="menu float-right">
<button class="btn btn-slash hover toggle-menu"><span class="relative z-10">menu</span></button>
</nav>
</header>
<main id="hero-canvas" class="relative clear-both w-full h-full">
</main>
</header>
</body>
</html>
Just in case if it's due to browser support, here is video screenshot how it looks on my end:
<div style="width: 100%; height: 0px; position: relative; padding-bottom: 56.250%;"><iframe src="https://streamable.com/e/npetvt" frameborder="0" width="100%" height="100%" allowfullscreen style="width: 100%; height: 100%; position: absolute;"></iframe></div>
Thank you in advance!

build semi circle progress bar with round corners and shadow in java script and CSS

I searched a lot and finding nothing on it. I want to make a progress bar with round corners.progress bar need to have shadow. All I did as of now is here :
$(".progress-bar").each(function(){
var bar = $(this).find(".bar");
var val = $(this).find("span");
var per = parseInt( val.text(), 10);
$({p:0}).animate({p:per}, {
duration: 3000,
easing: "swing",
step: function(p) {
bar.css({
transform: "rotate("+ (45+(p*1.8)) +"deg)"
});
val.text(p|0);
}
});
});
body{
background-color:#3F63D3;
}
.progress-bar{
position: relative;
margin: 4px;
float:left;
text-align: center;
}
.barOverflow{
position: relative;
overflow: hidden;
width: 150px; height: 70px;
margin-bottom: -14px;
}
.bar{
position: absolute;
top: 0; left: 0;
width: 150px; height: 150px;
border-radius: 50%;
box-sizing: border-box;
border: 15px solid gray;
border-bottom-color: white;
border-right-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress-bar">
<div class="barOverflow">
<div class="bar"></div>
</div>
<span>100</span>%
</div>
I want to make corners round and having shadow. below given image represent what actually i want. Shadow is missing because i don't know to draw. :
I have tried Progressbar.js also, but I don't have much knowledge about SVG. Any answer would be appreciated.
#jaromanda for suggestion of learning SVG.
Yes is looks very hard to achieve from border-radius. So i looked into SVG and find it pretty handy. Here is my snippet:
// progressbar.js#1.0.0 version is used
// Docs: http://progressbarjs.readthedocs.org/en/1.0.0/
var bar = new ProgressBar.SemiCircle(container, {
strokeWidth: 10,
color: 'red',
trailColor: '#eee',
trailWidth: 10,
easing: 'easeInOut',
duration: 1400,
svgStyle: null,
text: {
value: '',
alignToBottom: false
},
// Set default step function for all animate calls
step: (state, bar) => {
bar.path.setAttribute('stroke', state.color);
var value = Math.round(bar.value() * 100);
if (value === 0) {
bar.setText('');
} else {
bar.setText(value+"%");
}
bar.text.style.color = state.color;
}
});
bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';
bar.animate(0.45); // Number from 0.0 to 1.0
#container {
width: 200px;
height: 100px;
}
svg {
height: 120px;
width: 200px;
fill: none;
stroke: red;
stroke-width: 10;
stroke-linecap: round;
-webkit-filter: drop-shadow( -3px -2px 5px gray );
filter: drop-shadow( -3px -2px 5px gray );
}
<script src="https://rawgit.com/kimmobrunfeldt/progressbar.js/1.0.0/dist/progressbar.js"></script>
<link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600,800,900" rel="stylesheet" type="text/css">
<div id="container"></div>
I want to suggest some stupid but quick solution since you're already using position: absolute. You can add background color to the circles when your animation starts.
html:
<div class="progress-bar">
<div class="left"></div>
<div class="right"><div class="back"></div></div>
<div class="barOverflow">
<div class="bar"></div>
</div>
<span>0</span>%
</div>
css:
/** all your css here **/
body{
background-color:#3F63D3;
}
.progress-bar{
position: relative;
margin: 4px;
float: left;
text-align: center;
}
.barOverflow{
position: relative;
overflow: hidden;
width: 150px; height: 70px;
margin-bottom: -14px;
}
.bar{
position: absolute;
top: 0; left: 0;
width: 150px; height: 150px;
border-radius: 50%;
box-sizing: border-box;
border: 15px solid gray;
border-bottom-color: white;
border-right-color: white;
transform: rotate(45deg);
}
.progress-bar > .left {
position: absolute;
background: white;
width: 15px;
height: 15px;
border-radius: 50%;
left: 0;
bottom: -4px;
overflow: hidden;
}
.progress-bar > .right {
position: absolute;
background: white;
width: 15px;
height: 15px;
border-radius: 50%;
right: 0;
bottom: -4px;
overflow: hidden;
}
.back {
width: 15px;
height: 15px;
background: gray;
position: absolute;
}
jquery:
$(".progress-bar").each(function(){
var bar = $(this).find(".bar");
var val = $(this).find("span");
var per = parseInt( val.text(), 10);
var $right = $('.right');
var $back = $('.back');
$({p:0}).animate({p:per}, {
duration: 3000,
step: function(p) {
bar.css({
transform: "rotate("+ (45+(p*1.8)) +"deg)"
});
val.text(p|0);
}
}).delay( 200 );
if (per == 100) {
$back.delay( 2600 ).animate({'top': '18px'}, 200 );
}
if (per == 0) {
$('.left').css('background', 'gray');
}
});
https://jsfiddle.net/y86qs0a9/7/
Same as the answers above, I found it much easier to implement using SVG instead of pure CSS.
However I couldn't find a single simplistic implementation using only HTML and CSS, or at least with no libraries, no external scripts or no dependencies. I found that given the math that needs to be calculated to make the SVG transformations to represent the percentage, JS needs to be included (if someone knows how to achieve this with only HTML and CSS I'd love to learn how). But what the JS script does is not long or complex enough to justify the overhead of adding yet another dependency to my codebase.
The JS calculations are pretty easy once you read through. You need to calculate the coordinate for the end point of the gauge in the coordinate system of the SVG. so basic trig.
Most of the CSS is not even needed and I added just to style it and to make it pretty. You can add shadow or gradients same as you could with any HTML pure shape.
Here is the codePen https://codepen.io/naticaceres/pen/QWQeyGX
You can easily tinker with this code to achieve any kind of shape of circular gauge (full circle, lower half of the semi-circle, or any variation including ellipsis).
Hope this is helpful.
// # Thanks to mxle for the first rounded corner CSS only solution https://stackoverflow.com/a/42478006/4709712
// # Thanks to Aniket Naik for the styling and the basic idea and implementation https://codepen.io/naikus/pen/BzZoLL
// - Aniket Naik has a library, linked to that codepen you should check out if you don't want to copy-paste or implement yourself
// the arc radius in the meter-value needs to stay the same, and must always be x=y, not lower than the possible circle that can connect the two points (otherwise the ratio is not preserved and the curvature doesn't match the background path).
// to style the gauge, make it bigger or smaller, play with its parent element and transform scale. don't edit width and height of SVG directly
function percentageInRadians(percentage) {
return percentage * (Math.PI / 100);
}
function setGaugeValue(gaugeElement, percentage, color) {
const gaugeRadius = 65;
const startingY = 70;
const startingX = 10;
const zeroBasedY = gaugeRadius * Math.sin(percentageInRadians(percentage));
const y = -zeroBasedY + startingY;
const zeroBasedX = gaugeRadius * Math.cos(percentageInRadians(percentage));
const x = -zeroBasedX + gaugeRadius + startingX;
// # uncomment this to log the calculations of the coordinates for the final point of the gauge value path.
//console.log(
// `percentage: ${percentage}, zeroBasedY: ${zeroBasedY}, y: ${y}, zeroBasedX: ${zeroBasedX}, x: ${x}`
//);
gaugeElement.innerHTML = `<path d="M ${startingX} ${startingY}
A ${gaugeRadius} ${gaugeRadius} 0 0 1 ${x} ${y}
" stroke="${color}" stroke-width="10" stroke-linecap="round" />`;
}
percentageChangedEvent = (gauge, newPercentage, color) => {
const percentage =
newPercentage > 100 ? 100 : newPercentage < 0 ? 0 : newPercentage;
setGaugeValue(gauge, percentage, color);
};
function initialGaugeSetup(gaugeElementId, inputId, meterColor, initialValue) {
const gaugeElement = document.getElementById(gaugeElementId);
setGaugeValue(gaugeElement, 0, meterColor);
const inputElement = document.getElementById(inputId);
inputElement.value = initialValue;
setGaugeValue(gaugeElement, initialValue, meterColor);
inputElement.addEventListener("change", (event) =>
percentageChangedEvent(gaugeElement, event.target.value, meterColor)
);
}
// Gauge Initial Config
initialGaugeSetup(
"svg-graph-meter-value",
"svg-gauge-percentage-2",
"rgb(227 127 215)",
40
);
body {
background-color: rgba(0, 0, 0, 0.8);
color: #999;
font-family: Hevletica, sans-serif;
}
/* SVG Path implementation */
.svg-container {
margin: 20px auto 10px;
height: 80px;
width: 150px;
}
svg {
fill: transparent;
}
.input-percent-container {
text-align: center;
}
.input-percent-container>* {
display: inline;
}
input {
text-align: right;
width: 40px;
margin: auto;
background-color: #5d5d5d;
color: white;
border-radius: 6px;
border: black;
}
<div class="svg-container">
<svg width="150" height="80" xmlns="http://www.w3.org/2000/svg">
<path d="M 10 70
A 65 65 0 1 1 140 70
" stroke="grey" stroke-width="3" stroke-linecap="round" />
<g id="svg-graph-meter-value">
</g>
</svg>
</div>
<div class="input-percent-container"><input id="svg-gauge-percentage-2" /><span>%<span/></div>

Fluid Box jQuery plugin not working

Can someone please tell me why my fluid box isn't working for my photo. I've followed all of the instructions to create the code for the fluidbox, but my photo doesn't show up on the webpage. But when you click on where it is supposed to be on the webpage, it takes you to another page that has my photo in it. Here is my codes:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootswatch: Cosmo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./bootstrap.css" media="screen">
<link rel="stylesheet" href="bootstrap-lightbox.css">
<link rel="stylesheet" href="portfoliostyle.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../bower_components/html5shiv/dist/html5shiv.js"></script>
<script src="../bower_components/respond/dest/respond.min.js"></script>
<![endif]-->
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-23019901-1']);
_gaq.push(['_setDomainName', "bootswatch.com"]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script src="jquery.js"></script>
<script src="imagelightbox.js"></script>
<script>
$( function()
{
$( 'a' ).imageLightbox();
});
</script>
</head>
<body>
<ul class="navigation">
<li class="nav-item">Home</li>
<li class="nav-item">Portfolio</li>
<li class="nav-item">About</li>
<li class="nav-item">Blog</li>
<li class="nav-item">Contact</li>
</ul>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger"></label>
<div class="site-wrap">
<div class="gallery">
<a class="space" href="images/spacetime.jpg" title="A Space in Time" data-fluidbox>
<img src="images/spacetime.jpg" />
</a>
<a href="images/spacetime.jpg" data-fluidbox>
<div class="fluidbox-wrap">
<img src="images/spacetime.jpg" />
<div class="fluidbox-ghost"></div>
</div>
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
$(function () {
// Global variables
var $fb = $('a[data-fluidbox');
vpRatio; // To store viewport aspect ratio
// Add class to all Fluidboxes
$fb.addClass('fluidbox');
// Create fluidbox modal background
$('body').append('<div id="fluidbox-overlay"></div>');
// Functions:
// 1. to close any opened Fluidbox
// 2. to position Fluidbox dynamically
var closeFb = function (){
$('a[data-fluidbox].fluidbox-opened').trigger('click');
},
positionFb = function ($activeFb){
// Get elements
var $img = $activeFb.find('img'),
$ghost = $activeFb.find('.fluidbox-ghost');
// Calculate offset and scale
var offsetY = $(window).scrollTop()-$img.offset().top+0.5*($img.data('imgHeight')*($img.data('imgScale')-1))+0.5*($(window).height()-$img.data('imgHeight')*$img.data('imgScale')),
offsetX = 0.5*($img.data('imgWidth')*($img.data('imgScale')-1))+0.5*($(window).width()- $img.data('imgWidth')*$img.data('imgScale')) - $img.offset().left,
scale = $img.data('imgScale');
// Animate wrapped elements
// Parse integers:
// 1. Offsets can be integers
// 2. Scale is rounded to nearest 2 decimal places
$ghost.css({ 'transform': 'translate('+parseInt(offsetX*10)/10+'px,'+parseInt(offsetY*10)/10+'px) scale('+parseInt(scale*1000)/1000+')' });
}
// The following events will force FB to close
//ā€Š... when the opqaue overlay is clicked upon
$('#fluidbox-bg').click(closeFb);
})();
$fb.imagesLoaded().done(function (){
$fb
.wrapInner('<div class="fluidbox-wrap" />')
.find('img')
.css({ opacity: 1 })
.after('<div class="fluidbox-ghost" />');
// Listen to resize event for calculations
$(window).resize(function (){
// Get viewport aspect ratio (#1)
vpRatio = $(window).width() / $(window).height();
// Get dimensions and aspect ratios
$fb.each(function (){
var $img = $(this).find('img'),
$ghost = $(this).find('.fluidbox-ghost'),
$wrap = $(this).find('.fluidbox-wrap'),
data = $img.data();
// Save image dimensions as jQuery object (#2)
data.imgWidth = $img.width();
data.imgHeight = $img.height();
data.imgRatio = $img.width() / $img.height();
// Resize ghost element (#3)
$ghost.css({
width: $img.width(),
height: $img.height(),
top: $img.offset().top - $wrap.offset().top,
left: $img.offset().left - $wrap.offset().left
});
// Calculate scale based on orientation (#4)
if(vpRatio > data.imgRatio) {
data.imgScale = $(window).height()*.95 / $img.height();
} else {
data.imgScale = $(window).width()*.95 / $img.width();
}
});
}).resize();
// Bind click event
$fb.click(function (e){
// Variables
var $img = $(this).find('img'),
$ghost = $(this).find('.fluidbox-ghost'),
$wrap = $(this).find('.fluidbox-wrap');
if($(this).data('fluidbox-state') == 0 || !$(this).data('fluidbox-state')) {
// State: Closed
// Action: Open Fluidbox
$(this)
.data('fluidbox-state', 1)
.removeClass('fluidbox-closed')
.addClass('fluidbox-opened');
// Show overlay
$('#fluidbox-overlay').fadeIn();
// Set thumbnail image source as background image first.
// We also show the ghost element
$ghost.css({
'background-image': 'url('+$img.attr('src')+')',
opacity: 1
});
// Hide original image
$img.css({ opacity: 0 });
// Preload ghost image
var ghostImg = new Image();
ghostImg.onload = function (){ $ghost.css({ 'background-image': 'url('+$activeFb.attr('href')+')' } ); };
ghostImg.src = $(this).attr('href');
// Position Fluidbox
positionFb($(this));
} else {
// State: Opened
// Action: Close Fluidbox
/// Switch state
$(this)
.data('fluidbox-state', 0)
.removeClass('fluidbox-opened')
.addClass('fluidbox-closed');
// Hide overlay
$('#fluidbox-overlay').fadeOut();
// Show original image
$img.css({ opacity: 1 });
// Hide ghost image
$ghost.css({ opacity: 0 });
// Reverse animation on wrapped elements
$ghost
.css({ 'transform': 'translate(0,0) scale(1)' })
.one('webkitTransitionEnd MSTransitionEnd oTransitionEnd transitionend', function (){
// Wait for transntion to run its course first
$ghost.css({ opacity: 0 });
});
}
});
</script>
CSS:
/* Navigation Menu - Background */
.navigation {
/* critical sizing and position styles */
width: 100%;
height: 100%;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 0;
/* non-critical appearance styles */
list-style: none;
background: #111;
}
/* Navigation Menu - List items */
.nav-item {
/* non-critical appearance styles */
width: 200px;
border-top: 1px solid #111;
border-bottom: 1px solid #000;
}
.nav-item a {
/* non-critical appearance styles */
display: block;
padding: 1em;
background: linear-gradient(135deg, rgba(0,0,0,0) 0%,rgba(0,0,0,0.65) 100%);
color: white;
font-size: 1.2em;
text-decoration: none;
transition: color 0.2s, background 0.5s;
}
.nav-item a:hover {
color: #c74438;
background: linear-gradient(135deg, rgba(0,0,0,0) 0%,rgba(75,20,20,0.65) 100%);
}
.site-wrap {
min-width: 100%;
min-height: 100%;
background-color: #fff;
position: absolute;
top: 0;
bottom: 100%;
left: 0;
z-index: 1;
padding: 4em;
background-image: linear-gradient(135deg,
rgb(254,255,255) 0%,
rgb(221,241,249) 35%,
rgb(160,216,239) 100%);
background-size: 200%;
}
.name {
position: absolute;
top: 60%;
right:40%;
}
h3{
text-align: center;
top: 65%;
}
/* Nav Trigger */
.nav-trigger {
/* critical styles - hide the checkbox input */
position: absolute;
clip: rect(0, 0, 0, 0);
}
label[for="nav-trigger"] {
/* critical positioning styles */
position: fixed;
left: 15px; top: 15px;
z-index: 2;
/* non-critical apperance styles */
height: 30px;
width: 30px;
cursor: pointer;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' x='0px' y='0px' width='30px' height='30px' viewBox='0 0 30 30' enable-background='new 0 0 30 30' xml:space='preserve'><rect width='30' height='6'/> <rect y='24' width='30' height='6'/><rect y='12' width='30' height='6'/></svg>");
background-size: contain;
}
/* Make the Magic Happen */
.nav-trigger + label, .site-wrap {
transition: left 0.2s;
}
.nav-trigger:checked + label {
left: 215px;
}
.nav-trigger:checked ~ .site-wrap {
left: 200px;
box-shadow: 0 0 5px 5px rgba(0,0,0,0.5);
}
body {
/* Without this, the body has excess horizontal scroll when the menu is open */
overflow-x: hidden;
}
/* Additional non-critical styles */
h1, h3, p {
max-width: 600px;
margin: 0 auto 1em;
}
code {
padding: 2px;
background: #ddd;
}
/* Micro reset */
*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border- box;margin:0;padding:0;}
html, body { height: 100%; width: 100%; font-family: Helvetica, Arial, sans-serif; }
/* Image Lightbox Galley */
a[data-fluidbox] {
background-color: #eee;
border: none;
cursor: -webkit-zoom-in;
cursor: -moz-zoom-in;
margin-bottom: 1.5rem;
}
a[data-fluidbox].fluidbox-opened {
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out;
}
a[class^='float'] {
margin: 1rem;
margin-top: 0;
width: 33.33333%;
}
a.float-left {
float: left;
margin-left: 0;
}
a.float-right {
float: right;
margin-right: 0;
}
a[data-fluidbox] img {
display: block;
margin: 0 auto;
opacity: 0;
max-width: 100%;
transition: all .25s ease-in-out;
}
#fluidbox-overlay {
background-color: rgba(255,255,255,.85);
cursor: pointer;
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out;
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 500;
}
.fluidbox-wrap {
background-position: center center;
background-size: cover;
margin: 0 auto;
position: relative;
z-index: 400;
transition: all .25s ease-in-out;
}
.fluidbox-opened .fluidbox-wrap {
z-index: 600;
}
.fluidbox-ghost {
background-size: cover;
background-position: center center;
position: absolute;
transition: all .25s ease-in-out;
}
.space img{
height: 25%;
width: 50%
}

ball not falling into the box (javascript)

I created a simple website as follows:
When I enter any text in the prompt and click okay, then a ball will be dropped into 1st box, i.e., into Past Thoughts box. Here is the code:
HTML
<h1>
Welcome to zen module
</h1>
<p id="demo">
</p>
<div id="divn">
<canvas id="myCanvas" width="100" height="300" style="transform: inherit; margin: 30px;">
</canvas>
</div>
<div class="fixed-size-square" onclick="popup();">
<span>
Past Thoughts
</span>
</div>
<div class="size-square" onclick="popup();">
<span>
Present Thoughts
</span>
</div>
<div class="square" onclick="popup();">
<span>
Future Thoughts
</span>
</div>
<button>
I've no thoughts
</button>
JavaScript
var context;
var dx = 4;
var dy = 4;
var y = 25;
var x = 10;
var counter = 0;
function draw() {
context = myCanvas.getContext('2d');
context.clearRect(0, 0, 400, 400);
context.beginPath();
context.fillStyle = "red";
context.arc(x, y, 10, 0, Math.PI * 2, true);
context.closePath();
context.fill();
if (x < 0 || x > 100) dx = -dx;
if (y < 0 || y > 200) dy = 0;
//x+=dx;
y += dy;
}
function popup() {
var thought = prompt("Please enter your thought");
if (thought !== null) {
setInterval(draw, 10);
} else window.alert("You should enter a thought");
}
CSS
.fixed-size-square {
display: table;
background: green;
}
.fixed-size-square span {
display: table-cell;
text-align: center;
vertical-align: middle;
color: white
}
.size-square {
display: table;
background: green;
}
.size-square span {
display: table-cell;
text-align: center;
vertical-align: middle;
color: white
}
.square {
display: table;
background: green;
}
.square span {
display: table-cell;
text-align: center;
vertical-align: middle;
color: white
}
.fixed-size-square, .size-square, .square {
float: left;
margin: 20px;
zoom: 1;
position: relative;
top: -291px;
width: 150px;
height: 150px;
/*box-shadow: 10px 10px 5px #888888;*/
/*position: absolute;*/
/*margin: auto;*/
}
button {
position: relative;
margin: 0px auto;
}
/*.myCanvas {
z-index: 0px;
}*/
#divn {
margin: 0px auto;
}
The problem is: The ball stays behind the box when it falls. It isn't visible in the box. How can it be fixed?
Fiddle
You could use opacity: 0.5; on .fixed-size-square, .size-square, .square
DEMO
Edit: here's a DEMO with optimized CSS.
position:relative;z-index:10000px; would do the trick but would mess with the layout you have now. I'd suggest something like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function popup (n) {
var context;
var dx= 4;
var dy=4;
var y=25;
var elWidth=150;
var ballWidth=10;
var x=(elWidth+ballWidth)/2;
var counter = 0;
var myCanvas=document.getElementById('myCanvas'+n);
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,200,235);
context.beginPath();
context.fillStyle="red";
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
if(y>200){clearInterval(interval);}
if( y<0 || y>200)dy=0;
y+=dy;
myCanvas.className='active';
}
var interval=setInterval(draw,10);
}
</script>
<style>
html,body{margin:0;}
div.time {
display: table;
background: green;
float: left;
margin: 20px;
zoom: 1;
position: relative;
top: 75px;
left:35px;
width: 150px;
height: 150px;
}
span {
display: table-cell;
text-align: center;
vertical-align: middle;
color: white
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
canvas{
z-index:10000;
transform: inherit;
float: left;
margin: 20px;
zoom: 1;
position: relative;
top: -200px;
left:35px;
margin:20px;
}
#myCanvas1{clear:left;}
</style>
</head>
<body>
<div class="time"><span>Past Thoughts</span></div>
<div class="time"><span>Present Thoughts</span></div>
<div class="time"><span>Future Thoughts</span></div>
<canvas id="myCanvas1" width="150" height="235" onclick="popup(1)"></canvas>
<canvas id="myCanvas2" width="150" height="235" onclick="popup(2)"></canvas>
<canvas id="myCanvas3" width="150" height="235" onclick="popup(3)"></canvas>
</body>
</html>
http://fiddle.jshell.net/uvrkgrqs/show/
there's an z-index property on html to set which layer things are.

Categories

Resources