Unity3D WebGL Canvas Resizing Issue - html

I am having problems with my game - it resizes right on some computers but not others can anyone help see what's wrong? it's at http://pking.io
here's the issue on Chrome:
pking.io loading issue
but it works fine on firefox on Mac OS or when I right after I resize the window on chrome on Max OS it works correctly, and when I try it on Windows I have the same issue on Firefox as well like in the screenshot
CSS:
body { padding: 0; margin: 0px; width: 100%; height: 100% }
#unity-container { position: absolute }
#unity-container.unity-desktop { left: 0; top: 0; bottom: 0; }
#unity-container.unity-mobile { width: 100%; height: 100% }
#unity-canvas { background: url('background.jpg'); background- size:cover; no-repeat }
.unity-mobile #unity-canvas { width: 100%; height: 100% }
#unity-loading-bar { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); display: none }
#unity-logo { width: 154px; height: 154px; background: url('logo.png') no-repeat center }
#unity-progress-bar-empty { width: 141px; height: 18px; margin-top: 10px; background: url('progress-bar-empty-light.png') no-repeat center }
#unity-progress-bar-full { width: 0%; height: 18px; margin-top: 10px; background: url('progress-bar-full-light.png') no-repeat center } #unity-build-title { float: right; margin-right: 10px; line-height: 38px; font-family: arial; font-size: 18px }
HTML:
<div id="unity-container" class="unity-desktop">
<canvas id="unity-canvas"></canvas>
<div id="unity-loading-bar">
<div id="unity-logo"></div>
<div id="unity-progress-bar-empty">
<div id="unity-progress-bar-full"></div>
</div>
</div>
</div>
<script type="fb3e0aeb9b24d32156234654-text/javascript">
var buildUrl = "Build";
var loaderUrl = buildUrl + "/minimal.loader.js";
var config = {
dataUrl: buildUrl + "/minimal.data",
frameworkUrl: buildUrl + "/minimal.framework.js",
codeUrl: buildUrl + "/minimal.wasm",
streamingAssetsUrl: "StreamingAssets",
companyName: "K Corporation",
productName: "PKing.io",
productVersion: "0.4a",
};
var container = document.querySelector("#unity-container");
var canvas = document.querySelector("#unity-canvas");
var loadingBar = document.querySelector("#unity-loading-bar");
var progressBarFull = document.querySelector("#unity-progress-bar-full");
var oldContainerWidth = container.style.width;
var oldContainerHeight = container.style.height;
container.style.width = "100%";
container.style.height = "100%";
if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
container.className = "unity-mobile";
config.devicePixelRatio = 1;
} else {
canvas.style.width = "100%";
canvas.style.height = "100%";
}
loadingBar.style.display = "block";
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
loadingBar.style.display = "none";
// fullscreenButton.onclick = () => {
// unityInstance.SetFullscreen(1);
// };
container.style.width = oldContainerWidth;
container.style.height = oldContainerHeight;
}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);
</script>

You can adjust the else part here for the customize size if possible in the latest unity build.
if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
container.className = "unity-mobile";
config.devicePixelRatio = 1;
} else {
canvas.style.width = "100%"; // here it can be adjusted in px
canvas.style.height = "100%"; // in my case i used 1305px * 350px
}
loadingBar.style.display = "block";
For the older versions use
var myGame = UnityLoader.instantiate(gameContainer, "http://mydomain/myfolder/Build/mygame.json", {width: 800, height: 600});

Related

Is it possible to do a parallax effect using the img tag in html or does it have to be done by background?

I am new to working on css/html and I was trying to do parallax effect contained in some border radius but every time I try to do it using a background (url) it doesn't seem to do what I want it to, so I was wondering if it'd be possible to do it from the img tag?
You can solve your problem using JS. Check out the example below. It will work for you. Have a nice day.
$('.img-parallax').each(function() {
var $image = $(this);
var $imageParent = $(this).parent();
function parallaxImg () {
var speed = $image.data('speed');
var imageY = $imageParent.offset().top;
var winY = $(this).scrollTop();
var winH = $(this).height();
var parentH = $imageParent.innerHeight();
// The next pixel to show on screen
var winBottom = winY + winH;
// If block is shown on screen
if (winBottom > imageY && winY < imageY + parentH) {
// Number of pixels shown after block appear
var imgBottom = ((winBottom - imageY) * speed);
// Max number of pixels until block disappear
var imgTop = winH + parentH;
// Percentage between start showing until disappearing
var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
}
$image.css({ top: imgPercent + '%', transform: 'translate(-50%, -' + imgPercent + '%)' });
}
$(document).on({
scroll: function () {
parallaxImg();
}, ready: function () {
parallaxImg();
}
});
});
#import url(https://fonts.googleapis.com/css?family=Amatic+SC:400,700);
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
font-family: "Amatic SC", cursive;
}
.block {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
font-size: 16px;
}
.block h2 {
position: relative;
display: block;
text-align: center;
margin: 0;
top: 50%;
transform: translateY(-50%);
font-size: 10vw;
color: white;
font-weight: 400;
}
.img-parallax {
width: 100vmax;
z-index: -1;
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, 0);
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
<img src="https://unsplash.it/1920/1920/?image=1003" data-speed="-1" class="img-parallax">
<h2>Parallax 1</h2>
</div>
<div class="block">
<img src="https://unsplash.it/1920/1920/?image=1002" data-speed="1" class="img-parallax">
<h2>Parallax 2</h2>
</div>
<div class="block">
<img src="https://unsplash.it/1920/1920/?image=1014" data-speed="1" class="img-parallax">
<h2>Parallax 3</h2>
</div>

Circular window

I have this fiddle.
https://jsfiddle.net/oeuc8L9y/2/
If you click the background the coordinates where you clicked get centered.
Is it possible to make the pointer events only work inside the hole?
Since I'm using an image for the ring the whole thing blocks the pointer-events but if I set it to pointer-events: none; I can click trough the ring too.
This is good.
This is bad.
I assume a way would be to get the pixel coordinate and calculate if it's inside the hole but I feel like that would only work for a specific screen size and it'd break if resized.
tooltip_X = $("#x-coords");
tooltip_Y = $("#y-coords");
$("#background").on("mouseover", (e) => {
showTooltip(e);
});
$("#background").on("mousemove", (e) => {
updateCoords(e);
moveTooltip(e);
});
$("#background").on("mouseout", (e) => {
hideTooltip(e);
});
$("#background").on("click", (e) => {
move(e);
updateCoords(e);
});
function showTooltip(e) {
$("#tooltip").css("display", "block");
}
function hideTooltip(e) {
$("#tooltip").css("display", "none");
}
function moveTooltip(e) {
var left = 0;
var top = 0;
if (e.pageX + $("#tooltip").width() + 10 < document.body.clientWidth) {
left = e.pageX + 10;
} else {
left = document.body.clientWidth + 5 - $("#tooltip").width();
}
if (e.pageY + $("#tooltip").height() + 10 < document.body.clientHeight) {
top = e.pageY + 10;
} else {
top = document.body.clientHeight + 5 - $("#tooltip").height();
}
$("#tooltip").offset({ top: top, left: left });
}
function updateCoords(e) {
var mouse_x = e.clientX - $("#background").offset().left;
var mouse_y = e.clientY - $("#background").offset().top;
$("#x-coords").text(Number.parseInt(mouse_x));
$("#y-coords").text(Number.parseInt(mouse_y));
}
function move(e) {
var mouse_x = e.clientX - $("#background").offset().left;
var mouse_y = e.clientY - $("#background").offset().top;
var new_x = 0;
var new_y = 0;
if (mouse_x < 250) {
mouse_x = 250;
}
if (mouse_y < 250) {
mouse_y = 250;
}
if (mouse_x > 1670) {
mouse_x = 1670;
}
if (mouse_y > 950) {
mouse_y = 950;
}
new_x = -(mouse_x - 250);
new_y = -(mouse_y - 250);
$("#background").css("margin-top", new_y);
$("#background").css("margin-left", new_x);
}
#container {
position: relative;
width: 500px;
height: 500px;
overflow: hidden;
z-index: 100;
}
#ring {
position: absolute;
border-radius: 100%;
max-height: 500px;
max-width: 500px;
z-index: 90;
pointer-events: none;
}
#lens {
position: absolute;
border: 1px solid red;
/*
something to make it round
*/
z-index: 80;
pointer-events: none;
}
#background {
position: absolute;
width: 1920px;
height: 1200px;
background-image: url("https://wallpaperaccess.com/full/197542.jpg");
z-index: 80;
outline: 5px dotted purple;
outline-offset: -5px;
}
#tooltip {
position: absolute;
white-space: nowrap;
background: #ffffcc;
border: 1px solid black;
padding: 5px;
color: black;
z-index: 999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head> </head>
<body>
<div id="container">
<img id="ring" src="https://pngimg.com/uploads/circle/circle_PNG26.png" alt="Lens Ring" />
<div id="lens"></div>
<div id="background"></div>
<span id="tooltip"> Div Coords (<span id="x-coords"></span>,<span id="y-coords"></span>) </span>
</div>
</body>
</html>

switching .carousel height and width depening on landscape or portrait photo

I use the code below to fit my landscape(4:3) photo's in a carousel. But I would like to change the width and height of the .carousel depending on the photo(landscape or portrait). How can I do that?
html {
height: 100%;
width: 100%;
}
body {
height: 100%;
width: 100%;
display: block;
}
.carousel {
/* the percentages below are for a 4:3 landscape photo(1600x1200) */
height: 60%;
width: 70%;
}
/* I need to set height : 70%; and width: 60% for portrait */
Should I add an class to the carousel-item to indicate that it's a landscape or portrait photo?
Create one class for portrait and one for landscape. When the image loads or when you get the image size then determine if it is portrait or landscape and then add the appropriate class to the image or carousel container.
// list of images - as requested you can put this list in a separate js file
// make sure it is before the other code below
var imagesArray = ["https://lorempixel.com/300/500/animals/1", "https://lorempixel.com/300/500/animals/2", "https://lorempixel.com/500/300/animals/1","https://lorempixel.com/500/300/animals/2","https://lorempixel.com/500/300/city/1","https://lorempixel.com/300/500/city/2"];
// when the user clicks the random button
// we get a random image from our list of URLS
// and then set that as the source of the image
function displayImage(direction, isURL) {
var image = document.getElementById("myImage");
var label = document.getElementById("loadingLabel");
var list = imagesArray.slice(); //make a copy
var currentURL = image.src;
var currentIndex;
var index = 0;
var numberOfImages = list.length;
if (isURL==true) {
currentURL = direction;
}
currentIndex = list.indexOf(currentURL);
if (direction=="next") {
index = currentIndex>=list.length-1 ? 0 : currentIndex+1;
}
else if (direction=="previous") {
index = currentIndex<=0 ? list.length-1 : currentIndex-1;
}
else if (direction=="random") {
list.splice(currentIndex,1);
index = Math.floor(Math.random()*list.length);
}
else if (direction=="start") {
index = 0;
}
else if (direction=="end") {
index = list.length-1;
}
else if (isURL) {
if (currentIndex==-1) {
console.log("Image not found in images array. Check the URL");
return;
}
index = currentIndex;
}
else {
console.log("Direction not specified");
}
image.src = list[index];
label.innerHTML = "Loading " + list[index] + "...";
label.title = list[index];
updateNavigationLabel();
}
// this handles when the image has finished loading
// we check if the image is portrait or landscape
// if it is landscape we set the landscape class
// if it is portrait we set the portrait class
function imageLoadHandler(event) {
var image = document.getElementById("myImage");
var carousel = document.getElementById("myCarousel");
var label = document.getElementById("loadingLabel");
var width = image.naturalWidth;
var height = image.naturalHeight;
var isPortrait = width<height;
var isSquare = width==height;
carousel.classList.remove("portrait");
carousel.classList.remove("landscape");
var caption = width + "x" + height;
if (isPortrait) {
caption = "Portrait (" + caption + ")";
carousel.classList.add("portrait");
}
else if (isPortrait==false) {
caption = "Landscape (" + caption + ")";
carousel.classList.add("landscape");
}
image.caption = caption;
label.innerHTML = caption;
updateNavigationLabel();
}
function updateNavigationLabel() {
var image = document.getElementById("myImage");
var label = document.getElementById("navigationLabel");
var list = imagesArray.slice(); //make a copy
var numberOfImages = list.length;
var currentURL = image.src;
currentIndex = list.indexOf(currentURL);
label.innerHTML = currentIndex+1 +" of " + numberOfImages;
}
window.addEventListener("DOMContentLoaded", function() {
var element = document.getElementById("myImage");
var button = document.getElementById("button");
var carousel = document.getElementById("myCarousel");
// listen for when an image loads
element.addEventListener("load", imageLoadHandler);
// listen for when the user clicks on the random button
button.addEventListener("click", function() {
displayImage('random')
});
// Options - load an image when the page loads
// displayImage("start"); // use to load the first image
// displayImage("end"); // use to load the last image
// displayImage("random"); // use to load a random image
// displayImage("specified", "https://lorempixel.com/300/500/animals/2"); // use to load an image in the images array
displayImage("https://lorempixel.com/300/500/animals/2", true);
});
.landscape {
height: 60%;
width: 70%;
outline:2px solid blue;
}
.portrait {
height: 70%;
width: 60%;
outline:2px solid purple;
}
#myCarousel {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
#myImage {
position: absolute;
left: 50%;
transform: translateX(-50%);
outline: 1px dashed red;
height: 100%;
width: 100%;
object-fit: contain;
}
#button {
position: fixed;
right: 10px;
top: 50px;
}
#loadingLabel {
position: absolute;
bottom: -20px;
left: 50%;
transform: translateX(-50%);
font: 10px sans-serif;
white-space: nowrap;
}
#navigationLabel {
font: 10px sans-serif;
}
#navigation {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
font: 10px sans-serif;
}
<!-- optionally set images in separate file. order before the main javascript -->
<script src="myimages.js"></script>
<div id="myCarousel" class="landscape">
<img id="myImage">
<label id="loadingLabel"></label>
</div>
<button id="button">random</button>
<div id="navigation">
<button id="prev" onclick="displayImage('previous')">prev</button>
<label id="navigationLabel"></label>
<button id="next" onclick="displayImage('next')">next</button>
</div>

Fix div position with respect to another div when zoom

I have the following HTML. The problem is that I can not make the div with id="ladder" have the same position with respect to its parent div with id="grid" when I zoom in or out. here is the code snakes and Ladders
var gameBoard = {
createBoard: function(dimension, mount) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = '100';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = '1';
return gameBoard;
}
};
gameBoard.createBoard(10, "#grid");
function intialPosition() {
$("#1").append($("#player1"));
$("#1").append($("#player2"));
var currentPosition = parseInt($("#1").attr('id'));
return currentPosition;
}
var start = intialPosition();
var face1 = new Image();
face1.src = "http://s19.postimg.org/fa5etrfy7/image.gif";
var face2 = new Image();
face2.src = "http://s19.postimg.org/qb0jys873/image.gif";
var face3 = new Image();
face3.src = "http://s19.postimg.org/fpgoms1vj/image.gif";
var face4 = new Image();
face4.src = "http://s19.postimg.org/xgsb18ha7/image.gif";
var face5 = new Image();
face5.src = "http://s19.postimg.org/lsy96os5b/image.gif";
var face6 = new Image();
face6.src = "http://s19.postimg.org/4gxwl8ynz/image.gif";
function rollDice() {
var status = document.getElementById("status");
var random = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + random + ".src")
status.innerHTML = "You rolled " + random;
//if (random == 6) {
// status.innerHTML += "! You get a free turn!!";
//}
return random;
}
var currentPosition = start;
var random1;
function move() {
var m = 1;
random1 = rollDice();
destination = currentPosition + random1;
$('#' + destination).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
$('#' + destination).append($('#player' + m));
if (destination == 36) {
destination = 55;
$('#' + destination).append($('#' + "player" + m));
}
if (destination == 96) {
destination = 57;
$('#' + destination).append($('#' + "player" + m));
}
if (destination >= 100) {
destination = 100;
$('#' + destination).append($('#' + "player" + m));
alert("You Won!!!!!!!");
}
currentPosition = parseInt($('#' + destination).attr('id'));
return currentPosition;
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
position: relative;
/*margin: 5px;*/
/*margin: auto;*/
}
/*#grid{
position:relative;
}*/
table {
width: 100%;
position: relative;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
/*color: #FF0000 ;*/
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#100 {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#playerAndDiceSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
/*margin: 2px;*/
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
margin: 2%;
}
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="http://s19.postimg.org/otai9he2n/oie_e_RDOY2iqd5o_Q.gif" />
</div>
<div id="bigSnake">
<img src="http://s19.postimg.org/hrcknaagz/oie_485727s_RN4_KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<!--style="position: absolute; top: 597px; z-index: 1;"-->
<img src="http://s19.postimg.org/t108l496n/human_Piece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="http://s19.postimg.org/l6zmzq1dr/computer_Piece.png" />
</div>
</div>
<div id="playerAndDiceSection">
<div id="playerSection">
<div id="player1">
<img src="http://s19.postimg.org/t108l496n/human_Piece.png" />Player1
<!--<p>Player1</p>-->
</div>
<div id="player2">
<img src="http://s19.postimg.org/l6zmzq1dr/computer_Piece.png" />Player2
</div>
</div>
<div id="diceSection">
<img src="http://s19.postimg.org/fa5etrfy7/image.gif" name="mydice" onclick="move()" style="background-color: white;">
<h2 id="status"></h2>
</div>
</div>
</div>
</body>

Auto size fixed text to fill dynamic size container

I'm trying to recreate this game in JavaScript. For this game, I need cells with numbers in them.
I want the game to size to the available space in the browser. I've managed to do this by using vw and vh in combination with width and min-width (and height) as you can see in the example. If you size the viewport in which the cells are shown, the cells size along.
The problem
And now, I want the text in it to size along too. The container (the cell) resizes, and the font of the digit should size accordingly. I now used vmax as a unit, but this doesn't take the horizontal sizing into account. And since there is no min-font-size, I cannot do the same trick I used for the cells themselves.
No jQuery please
I've tried and searched. Most notably, I found Auto-size dynamic text to fill fixed size container, however I think my question is reversed. The text is fixed, and I could set an initial font-size. I just need the font to scale along with the size of the element, so maybe this can be done through CSS after all.
Besides, most questions about this subject suggest using one of the various jQuery plugins and I'm not looking for a jQuery solution. I'm trying to make this game just for fun and practice, and I've set a goal to create it without jQuery. Actually I'm not even looking for a vanilla JavaScript solution. In the end it may boil down to that, but I haven't tried building it myself yet, so I don't want to ask for JavaScript here now. No, I'm looking for a pure CSS solution, if any.
The snippet
The dressed down snippet works best in full page mode. Nevermind the inline styling. These elements are actually generated by JavaScript and need be moved around. And sorry for the chunk of HTML. I brought it down to two cells at first, but that looked confusing, because they only filled a small part of the screen, and you couldn't see what was going on.
.game11,
.game11 .cell,
.game11 .cell .digit {
box-sizing: border-box;
}
.game11 {
width: 90vw;
height: 90vw;
max-width: 90vh;
max-height: 90vh;
box-sizing: border-box;
position: relative;
}
.game11 .cell {
width: 20%;
height: 20%;
position: absolute;
font-size: 7vmax; /* Font size. This obviously doesn't work */
}
.game11 .cell .digit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 3px solid #666633;
text-align: center;
padding-top: 13%;
font-family: Impact, Charcoal, sans-serif;
color: #111111;
}
<div class="game11">
<div class="cell" style="left: 0%; top: 0%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 20%; top: 0%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 40%; top: 0%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 60%; top: 0%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 80%; top: 0%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 0%; top: 20%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 20%; top: 20%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 40%; top: 20%;">
<div class="digit digit4" style="top: 0px;">4</div>
</div>
<div class="cell" style="left: 60%; top: 20%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 80%; top: 20%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 0%; top: 40%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 20%; top: 40%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 40%; top: 40%;">
<div class="digit digit4" style="top: 0px;">4</div>
</div>
<div class="cell" style="left: 60%; top: 40%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 80%; top: 40%;">
<div class="digit digit4" style="top: 0px;">4</div>
</div>
<div class="cell" style="left: 0%; top: 60%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 20%; top: 60%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 40%; top: 60%;">
<div class="digit digit5" style="top: 0px;">5</div>
</div>
<div class="cell" style="left: 60%; top: 60%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 80%; top: 60%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 0%; top: 80%;">
<div class="digit digit4">4</div>
</div>
<div class="cell" style="left: 20%; top: 80%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 40%; top: 80%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 60%; top: 80%;">
<div class="digit digit5">5</div>
</div>
<div class="cell" style="left: 80%; top: 80%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
</div>
Updated: The 'full' (still unfinished) game, including the fix suggested by Pangloss
In the snippet below, you can find the game as I have it so far. It's working for the largest part, so if it's not helpful for the question, at least it may be fun or helpful to future visitors.
/**
* Game11 class
*/
function Game11(container) {
var game = this;
game.element = container;
game.cells = [];
game.highestValue = 4;
game.animations = [];
game.animating = false;
var four = this.random(25);
for (var i = 0; i < 25; i++) {
var cell = new Cell(game, i);
var value = this.random(3) + 1;
if (i == four)
value = 4;
cell.setValue(value);
game.cells[i] = cell;
}
}
Game11.prototype.random = function(to) {
return Math.floor(Math.random() * to);
}
Game11.prototype.cellClicked = function(cell) {
if (cell.selected) {
this.collapse(cell);
} else {
this.select(cell);
}
}
Game11.prototype.collapse = function(cell) {
var newValue = cell.value + 1;
if (newValue > this.highestValue) {
this.highestValue = newValue;
}
cell.setValue(newValue);
for (var i = 24; i >= 0; i--) {
if (this.cells[i].selected) {
if (i !== cell.index) {
this.cells[i].setValue(null);
}
this.cells[i].select(false);
}
}
for (var i = 24; i >= 0; i--) {
if (this.cells[i].value == null) {
this.cells[i].collapse();
}
}
this.animate();
}
Game11.prototype.select = function(cell) {
for (var i = 0; i < 25; i++) {
this.cells[i].select(false);
}
var selectCount = 0;
var stack = [];
stack.push(cell);
while (stack.length > 0) {
var c = stack.pop();
c.select(true);
selectCount++;
var ac = this.getAdjacentCells(c);
for (var i = 0; i < ac.length; i++) {
if (ac[i].selected == false && ac[i].value == cell.value) {
stack.push(ac[i]);
}
}
}
if (selectCount == 1)
cell.select(false);
}
Game11.prototype.getAdjacentCells = function(cell) {
var result = [];
if (cell.x > 0) result.push(this.cells[cell.index - 1]);
if (cell.x < 4) result.push(this.cells[cell.index + 1]);
if (cell.y > 0) result.push(this.cells[cell.index - 5]);
if (cell.y < 4) result.push(this.cells[cell.index + 5]);
return result;
}
Game11.prototype.registerAnimation = function(animation) {
this.animations.push(animation);
}
Game11.prototype.animate = function() {
this.animating = true;
var maxTicks = 300;
var start = new Date().valueOf();
var timer = setInterval(function(){
var tick = new Date().valueOf() - start;
if (tick >= maxTicks) {
tick = maxTicks;
this.animating = false;
}
var percentage = 100 / maxTicks * tick;
for (a = 0; a < this.animations.length; a++) {
this.animations[a].step(percentage);
}
if (this.animating === false) {
clearInterval(timer);
this.animations.length = 0;
console.log('x');
}
}.bind(this), 1);
}
/**
* A single cell
*/
function Cell(game, index) {
var cell = this;
cell.game = game;
cell.index = index;
cell.selected = false;
cell.element = document.createElement('div');
cell.element.className = 'cell';
cell.digit = document.createElement('div');
cell.digit.className = 'digit';
cell.element.appendChild(cell.digit);
cell.element.addEventListener('click', cell.clicked.bind(cell));
game.element.appendChild(cell.element);
cell.x = index % 5;
cell.y = Math.floor((index - cell.x) / 5);
cell.element.style.left = (cell.x * 20) + '%';
cell.element.style.top = (cell.y * 20) + '%';
}
Cell.prototype.clicked = function() {
this.game.cellClicked(this);
}
Cell.prototype.setValue = function(value) {
this.digit.classList.remove('digit' + this.value);
this.value = value;
if (value === null) {
this.digit.innerText = '';
} else {
this.digit.classList.add('digit' + value);
this.digit.innerText = value;
}
}
Cell.prototype.select = function(selected) {
this.element.classList.toggle('selected', selected);
this.selected = selected;
}
Cell.prototype.collapse = function() {
var value, y, cellHere, cellAbove;
var n = this.y;
var offset = 0;
do {
cellHere = this.game.cells[this.x + 5*n];
y = n - offset;
value = null;
do {
if (--y >= 0) {
cellAbove = this.game.cells[this.x + 5*y];
value = cellAbove.value;
cellAbove.setValue(null);
if (value !== null) {
console.log('Value ' + value + ' for cell (' + this.x+','+n+') taken from cell ' + y);
}
} else {
offset++;
value = this.game.random(Math.max(3, this.game.highestValue - 2)) + 1;
console.log('New value ' + value + ' for cell (' + this.x+','+n+')');
}
} while (value === null);
cellHere.animateDrop(value, n-y);
} while (--n >= 0)
}
Cell.prototype.animateDrop = function(value, distance) {
this.setValue(value);
new Animation(this.game, -distance, this.index, value);
}
/**
* A cell animation
*/
function Animation(game, from, to, value) {
this.toCell = game.cells[to];
var cellBounds = this.toCell.element.getBoundingClientRect();
var fromX = toX = cellBounds.left;
var fromY = toY = cellBounds.top;
if (from < 0) {
fromY += cellBounds.height * from;
} else {
// To do: Moving from one cell to another needs an extra sprite.
this.fromCell = game.cells[from];
cellBounds = this.fromCell.element.getBoundingClientRect();
var fromX = cellBounds.left;
var fromY = cellBounds.top;
}
this.fromX = fromX;
this.fromY = fromY;
this.toX = toX;
this.toY = toY;
this.to = to;
game.registerAnimation(this);
}
Animation.prototype.step = function(percentage) {
var distance = this.toY - this.fromY;
var step = (100-percentage) / 100;
var Y = step * distance;
this.toCell.digit.style.top = '' + (-Y) + 'px';
}
// Start the game
new Game11(document.querySelector('.game11'));
.game11,
.game11 .cell,
.game11 .cell .digit {
box-sizing: border-box;
}
.game11 {
width: 90vmin;
height: 90vmin;
box-sizing: border-box;
position: relative;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.game11 .cell {
width: 20%;
height: 20%;
border: 2px solid #ffffff;
position: absolute;
font-size: 10vmin;
}
.game11 .cell .digit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 3px solid #666633;
text-align: center;
padding-top: 13%;
font-family: Impact, Charcoal, sans-serif;
color: #111111;
}
.game11 .cell.selected .digit {
color: white;
}
.game11 .digit.digit1 {
background-color: #CC66FF;
}
.game11 .digit.digit2 {
background-color: #FFCC66;
}
.game11 .digit.digit3 {
background-color: #3366FF;
}
.game11 .digit.digit4 {
background-color: #99CCFF;
}
.game11 .digit.digit5 {
background-color: #19D119;
}
.game11 .digit.digit6 {
background-color: #009999;
}
.game11 .digit.digit7 {
background-color: #996600;
}
.game11 .digit.digit8 {
background-color: #009933;
}
.game11 .digit.digit9 {
background-color: #666699;
}
.game11 .digit.digit10 {
background-color: #CC66FF;
}
.game11 .digit.digit11,
.game11 .digit.digitmax {
background-color: #FF0066;
}
<div class="game11">
</div>
You could set font size to vmin value.
.game11 .cell {
font-size: 10vmin;
}
http://jsfiddle.net/a21s77c8/
If there is no CSS solution, you can do it by JavaScript. This is quite easy, since all the game's cells are squared and the same size, so you can just get the font size as a factor of the game width. Because of these boundaries, there is no need for a complex library.
All you need to do is remove the font-size from the CSS and add this piece of code to the constructor of Game11:
// Function that calculates font size based on width of the game itself.
var updateFontSize = function() {
var bounds = game.element.getBoundingClientRect(); // Game
var size = bounds.width / 5; // Cell
size *= 0.6; // Font a bit smaller
game.element.style.fontSize = size + 'px';
};
// Attach to resize event.
window.addEventListener('resize', updateFontSize);
// Initial font size calculation.
updateFontSize();
Updated game:
/**
* Game11 class
*/
function Game11(container) {
var game = this;
game.element = container;
game.cells = [];
game.highestValue = 4;
game.animations = [];
game.animating = false;
var four = this.random(25);
// Function that calculates font size based on width of the game itself.
var updateFontSize = function() {
var bounds = game.element.getBoundingClientRect(); // Game
var size = bounds.width / 5; // Cell
size *= 0.6; // Font a bit smaller
game.element.style.fontSize = size + 'px';
};
// Attach to resize event.
window.addEventListener('resize', updateFontSize);
// Initial font size calculation.
updateFontSize();
for (var i = 0; i < 25; i++) {
var cell = new Cell(game, i);
var value = this.random(3) + 1;
if (i == four)
value = 4;
cell.setValue(value);
game.cells[i] = cell;
}
}
Game11.prototype.random = function(to) {
return Math.floor(Math.random() * to);
}
Game11.prototype.cellClicked = function(cell) {
if (cell.selected) {
this.collapse(cell);
} else {
this.select(cell);
}
}
Game11.prototype.collapse = function(cell) {
var newValue = cell.value + 1;
if (newValue > this.highestValue) {
this.highestValue = newValue;
}
cell.setValue(newValue);
for (var i = 24; i >= 0; i--) {
if (this.cells[i].selected) {
if (i !== cell.index) {
this.cells[i].setValue(null);
}
this.cells[i].select(false);
}
}
for (var i = 24; i >= 0; i--) {
if (this.cells[i].value == null) {
this.cells[i].collapse();
}
}
this.animate();
}
Game11.prototype.select = function(cell) {
for (var i = 0; i < 25; i++) {
this.cells[i].select(false);
}
var selectCount = 0;
var stack = [];
stack.push(cell);
while (stack.length > 0) {
var c = stack.pop();
c.select(true);
selectCount++;
var ac = this.getAdjacentCells(c);
for (var i = 0; i < ac.length; i++) {
if (ac[i].selected == false && ac[i].value == cell.value) {
stack.push(ac[i]);
}
}
}
if (selectCount == 1)
cell.select(false);
}
Game11.prototype.getAdjacentCells = function(cell) {
var result = [];
if (cell.x > 0) result.push(this.cells[cell.index - 1]);
if (cell.x < 4) result.push(this.cells[cell.index + 1]);
if (cell.y > 0) result.push(this.cells[cell.index - 5]);
if (cell.y < 4) result.push(this.cells[cell.index + 5]);
return result;
}
Game11.prototype.registerAnimation = function(animation) {
this.animations.push(animation);
}
Game11.prototype.animate = function() {
this.animating = true;
var maxTicks = 300;
var start = new Date().valueOf();
var timer = setInterval(function(){
var tick = new Date().valueOf() - start;
if (tick >= maxTicks) {
tick = maxTicks;
this.animating = false;
}
var percentage = 100 / maxTicks * tick;
for (a = 0; a < this.animations.length; a++) {
this.animations[a].step(percentage);
}
if (this.animating === false) {
clearInterval(timer);
this.animations.length = 0;
console.log('x');
}
}.bind(this), 1);
}
/**
* A single cell
*/
function Cell(game, index) {
var cell = this;
cell.game = game;
cell.index = index;
cell.selected = false;
cell.element = document.createElement('div');
cell.element.className = 'cell';
cell.digit = document.createElement('div');
cell.digit.className = 'digit';
cell.element.appendChild(cell.digit);
cell.element.addEventListener('click', cell.clicked.bind(cell));
game.element.appendChild(cell.element);
cell.x = index % 5;
cell.y = Math.floor((index - cell.x) / 5);
cell.element.style.left = (cell.x * 20) + '%';
cell.element.style.top = (cell.y * 20) + '%';
}
Cell.prototype.clicked = function() {
this.game.cellClicked(this);
}
Cell.prototype.setValue = function(value) {
this.digit.classList.remove('digit' + this.value);
this.value = value;
if (value === null) {
this.digit.innerText = '';
} else {
this.digit.classList.add('digit' + value);
this.digit.innerText = value;
}
}
Cell.prototype.select = function(selected) {
this.element.classList.toggle('selected', selected);
this.selected = selected;
}
Cell.prototype.collapse = function() {
var value, y, cellHere, cellAbove;
var n = this.y;
var offset = 0;
do {
cellHere = this.game.cells[this.x + 5*n];
y = n - offset;
value = null;
do {
if (--y >= 0) {
cellAbove = this.game.cells[this.x + 5*y];
value = cellAbove.value;
cellAbove.setValue(null);
if (value !== null) {
console.log('Value ' + value + ' for cell (' + this.x+','+n+') taken from cell ' + y);
}
} else {
offset++;
value = this.game.random(Math.max(3, this.game.highestValue - 2)) + 1;
console.log('New value ' + value + ' for cell (' + this.x+','+n+')');
}
} while (value === null);
cellHere.animateDrop(value, n-y);
} while (--n >= 0)
}
Cell.prototype.animateDrop = function(value, distance) {
this.setValue(value);
new Animation(this.game, -distance, this.index, value);
}
/**
* A cell animation
*/
function Animation(game, from, to, value) {
this.toCell = game.cells[to];
var cellBounds = this.toCell.element.getBoundingClientRect();
var fromX = toX = cellBounds.left;
var fromY = toY = cellBounds.top;
if (from < 0) {
fromY += cellBounds.height * from;
} else {
// To do: Moving from one cell to another needs an extra sprite.
this.fromCell = game.cells[from];
cellBounds = this.fromCell.element.getBoundingClientRect();
var fromX = cellBounds.left;
var fromY = cellBounds.top;
}
this.fromX = fromX;
this.fromY = fromY;
this.toX = toX;
this.toY = toY;
this.to = to;
game.registerAnimation(this);
}
Animation.prototype.step = function(percentage) {
var distance = this.toY - this.fromY;
var step = (100-percentage) / 100;
var Y = step * distance;
this.toCell.digit.style.top = '' + (-Y) + 'px';
}
// Start the game
new Game11(document.querySelector('.game11'));
.game11,
.game11 .cell,
.game11 .cell .digit {
box-sizing: border-box;
}
.game11 {
width: 90vw;
height: 90vw;
max-width: 90vh;
max-height: 90vh;
box-sizing: border-box;
position: relative;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.game11 .cell {
width: 20%;
height: 20%;
border: 2px solid #ffffff;
position: absolute;
}
.game11 .cell .digit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 3px solid #666633;
text-align: center;
padding-top: 13%;
font-family: Impact, Charcoal, sans-serif;
color: #111111;
}
.game11 .cell.selected .digit {
color: white;
}
.game11 .digit.digit1 {
background-color: #CC66FF;
}
.game11 .digit.digit2 {
background-color: #FFCC66;
}
.game11 .digit.digit3 {
background-color: #3366FF;
}
.game11 .digit.digit4 {
background-color: #99CCFF;
}
.game11 .digit.digit5 {
background-color: #19D119;
}
.game11 .digit.digit6 {
background-color: #009999;
}
.game11 .digit.digit7 {
background-color: #996600;
}
.game11 .digit.digit8 {
background-color: #009933;
}
.game11 .digit.digit9 {
background-color: #666699;
}
.game11 .digit.digit10 {
background-color: #CC66FF;
}
.game11 .digit.digit11,
.game11 .digit.digitmax {
background-color: #FF0066;
}
<div class="game11">
</div>
Still, if it could be done through CSS, that'd be great.