I need to distribute points evenly on a circumference of a circle, and I'm out of my wits. The result is not exactly circular but rather spiraly, especially with larger numbers of points. I've researched it vigorously but still can't figure out where I could make a mistake.
window.onload = function() {
var num = 15;
var angle = (2 * Math.PI)/(num+1); var count = 0;
var demo = document.getElementById("demo");
function Dot() {
this.angle = angle * count;
count++;
this.x = Math.cos(this.angle) * 200;
this.y = Math.sin(this.angle) * 200;
}
Dot.prototype.create = function() {
var dot = document.createElement("div");
dot.style.top = this.y + 100 + "px";
dot.style.left = this.x + 200 + "px";
dot.className = "dot";
demo.appendChild(dot);
}
for (var i = 0; i < num; i++) {
var d = new Dot();
d.create();
}
}
.dot {
height: 20px;
width: 20px;
border-radius: 50%;
background: blue;
position: relative;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>Metcalfe's Law Demo</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="container">
<div id="demo">
</div>
</div>
</body>
</html>
The main mistake is bloody simple - just change the style position: relative to position: absolute:
window.onload = function() {
var num = 12;
var angle = (2 * Math.PI)/(num); var count = 0;
var demo = document.getElementById("demo");
console.log(angle)
function Dot() {
this.angle = angle * count;
count++;
console.log(this.angle,count)
this.x = Math.cos(this.angle) * 200;
this.y = Math.sin(this.angle) * 200;
}
Dot.prototype.create = function() {
var dot = document.createElement("div");
dot.style.top = this.y + 200 + "px";
dot.style.left = this.x + 200 + "px";
dot.className = "dot";
demo.appendChild(dot);
}
for (var i = 0; i < num; i++) {
var d = new Dot();
d.create();
}
}
.dot {
height: 20px;
width: 20px;
border-radius: 50%;
background: blue;
position: absolute;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>Metcalfe's Law Demo</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="container">
<div id="demo">
</div>
</div>
</body>
</html>
Related
I have this code that after a while starts to slow down, I tried everything to reduce the script and increase performance but nothing works.
Here's a snippet with the code:
var rotated = false;
function load() {
setInterval(rain, 100);
function rain() {
var deg = rotated ? 0 : 20;
var variable = screen.width + screen.width;
var side = Math.floor((Math.random() * variable));
var pos = -20;
var element = document.createElement('div');
var position = Math.random() < 0.5 ? 1 : 3;
element.style.webkitTransform = 'rotate(' + deg + 'deg)';
element.style.mozTransform = 'rotate(' + deg + 'deg)';
element.style.msTransform = 'rotate(' + deg + 'deg)';
element.style.oTransform = 'rotate(' + deg + 'deg)';
element.style.transform = 'rotate(' + deg + 'deg)';
element.style.position = "absolute";
element.style.width = "1px";
element.style.height = "10px";
element.style.top = "-20px";
element.style.zIndex = position;
document.getElementById('body').appendChild(element);
if (position == 3) {
element.style.backgroundColor = "#0018FF";
}
if (position == 1) {
element.style.backgroundColor = "#8590FF";
}
element.style.left = side + 'px';
setInterval(frame, 1);
setInterval(frame2, 2);
setInterval(frameChecker, 100);
function frame() {
pos++;
element.style.top = pos + 'px';
}
function frame2() {
side--;
element.style.left = side + "px";
}
function frameChecker() {
element.id = pos;
if (element.id > screen.height + 500) {
element.remove();
}
}
}
}
body {
font-family: "Times New Roman", Times, serif;
}
html,
body {
padding: 0px;
margin: 0px;
width: 100%;
height: 100%;
overflow: hidden;
background-color: black
}
.center {
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
position: absolute;
text-align: center;
z-index: 2;
}
.center span {
position: relative;
font-size: 500%;
text-align: center;
top: 45%;
transform: translateY(-50%);
color: white
}
<!DOCTYPE html>
<html>
<head>
<!--CSS and SCRIPT here-->
<title>GOT 404 ERROR</title>
</head>
<body onload="load()" id="body">
<div style="width:100%; height:100%; position: relative;">
<div class="center"><span>ERROR 404</span></div>
</div>
</body>
</html>
The whole JavaScript code is to make it rain, I think the problem is in somewhere in the variables but when I set as global only one dot of "rain" shows up (by global i mean outside of any function)
so i done it:
every 100 miliseconds is added a dot, this dot start 3 functions/dot to move and check its location, so i just added a "interval cleaner",(the frameChecker() if settement here is the code:
<!DOCTYPE html>
<html>
<head>
<style>
body{
font-family: "Times New Roman", Times, serif;}
html, body{
padding: 0px;
margin: 0px;
width: 100%;
height: 100%;
overflow: hidden;
background-color: black}
.center {
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
position: absolute;
text-align: center;
z-index: 2;}
.center span{
position: relative;
font-size: 500%;
text-align: center;
top: 45%;
transform: translateY(-50%);
color: white}
</style>
<script type="text/javascript">
var rotated = false;
function load(){
setInterval(rain, 200);
function rain(){
var deg = rotated ? 0 : 20;
var variable = screen.width+screen.width;
var side = Math.floor((Math.random() * variable));
var pos = -20;
var element = document.createElement('div');
var position = Math.random() < 0.5 ? 1 : 3;
element.style.webkitTransform = 'rotate('+deg+'deg)';
element.style.mozTransform = 'rotate('+deg+'deg)';
element.style.msTransform = 'rotate('+deg+'deg)';
element.style.oTransform = 'rotate('+deg+'deg)';
element.style.transform = 'rotate('+deg+'deg)';
element.style.position = "absolute";
element.style.width = "1px";
element.style.height = "10px";
element.style.top = "-20px";
element.style.zIndex = position;
document.getElementById('body').appendChild(element);
if (position == 3){element.style.backgroundColor = "#0018FF";}
if (position == 1){element.style.backgroundColor = "#8590FF";}
element.style.left = side + 'px';
var framee = setInterval(frame, 1);
var framee2 = setInterval(frame2, 2);
var frameCheckerr = setInterval(frameChecker, 100);
function frame() {
pos++;
element.style.top = pos + 'px';}
function frame2() {
side--;
element.style.left = side + "px";}
function frameChecker(){
element.id = pos;
if (element.id > screen.height+20){element.remove();clearInterval(framee);clearInterval(framee2);clearInterval(frameCheckerr);}}}}
</script>
<title>GOT 404 ERROR</title>
</head>
<body onload="load()" id="body">
<div style="width:100%; height:100%; position: relative;">
<div class="center"><span>ERROR 404</span></div>
</div>
</body>
</html>
it was petty tuff to fund out, thanks to #Pointy for saying about the functions being allways on after called with setInterval() and also the first timer (rain()) can be used with timer set was 500 for better performace
Every time your rain() function runs because of its interval timer (every 100 milliseconds), it starts three new interval timers with even faster intervals. After a minute or so, therefore, you'll have hundreds of interval timers running. That's what is making everything slow down.
You might consider setTimeout() for those nested functions. The setTimeout function calls it's callback only once after a single delay.
I am trying to create a grid which takes a user input and uses that as its number of rows and columns. In other words, if the user inputs X, I want the grid to have X rows and X columns, and be square, meaning the boxes are as high as they are wide.
I have gotten it to work with JavaScript and CSS grid, but only if I already know the number of rows/columns, in that case 10. Please see below.
How can I create a grid that does the same but with any number of rows and columns?
#container {
display: grid;
grid-template-columns: repeat(10, 1fr);
width: 500px;
height: 500px;
}
div {
width: 100%;
height: 100%;
outline: 1px solid;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
</body>
<script>
let btn = document.getElementById("start")
btn.addEventListener("click", createGrid)
function createGrid() {
let numberOfRows = prompt("How many rows do you want?");
let i = 0;
let x = numberOfRows ** 2;
for (i; i < x; i++) {
var div = document.createElement("div");
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function() {
this.style.backgroundColor = "red";
});
}
}
</script>
</html>
You can use CSS variable for that. and change the variable value using javascript.
let btn = document.getElementById("start")
btn.addEventListener("click", createGrid)
function createGrid() {
var Container = document.getElementById("container");
Container.innerHTML = '';
let numberOfRows = prompt("How many rows do you want?");
let i = 0;
let x = numberOfRows * numberOfRows;
document.documentElement.style.setProperty("--columns-row", numberOfRows);
for (i = 0; i < x ; i++) {
var div = document.createElement("div");
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function () {
this.style.backgroundColor = "red";
});
}
}
:root {
--columns-row: 2;
}
#container {
display: grid;
grid-template-columns: repeat(var(--columns-row), 1fr);
grid-template-rows: repeat(var(--columns-row), 1fr);
width: 500px;
height: 500px;
}
div {
border: 1px solid #000;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container">
</div>
</body>
</html>
Change your css as per your need. jsfiddle.net/926pd5oh/9
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
<style>
#container>div {
width: 100%;
height: 10px;
margin: 2px;
}
#container>div>div {
float: left;
height: 10px;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
width: 25px;
}
</style>
<script>
let btn = document.getElementById("start")
btn.addEventListener("click", createGrid);
function createGrid() {
let numberOfRows = prompt("How many rows do you want?");
document.getElementById("container").innerHTML = "";
console.log(numberOfRows);
for (let i = 0; i < numberOfRows; i++) {
var divRow = document.createElement("div");
document.getElementById("container").appendChild(divRow);
for (let y = 0; y < numberOfRows; y++) {
let divCol = document.createElement("div");
divCol.addEventListener("mouseenter", function () {
this.style.backgroundColor = "red";
});
divRow.appendChild(divCol);
}
}
}
</script>
I've ended up using a different tool: container.style.gridTemplateColumns and container.style.gridTemplateRows to affect the number of rows and columns of the container. This allows me not to use the :root function above. See JavaScript Syntax at https://www.w3schools.com/cssref/pr_grid-template-columns.asp
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
</body>
<script>
//randomColor function is taken from http://www.devcurry.com/2010/08/generate-random-colors-using-javascript.html //
function randomRgb(value) {
col = "rgb("
+ randomColor(255) * value + ","
+ randomColor(255) * value + ","
+ randomColor(255) * value + ")";
}
function randomColor(num) {
return Math.floor(Math.random() * num);
}
function resetColorOfBoxes() {
boxes = document.querySelectorAll('div');
boxes.forEach(box => box.style.backgroundColor = "white");
}
function promptEntry() {
let userInput = prompt("How many rows would you like?", "Enter a number");
if (isNaN(userInput)) {
alert("That's not a valid entry. Try again");
promptEntry();
}
else {
createGrid(userInput);
}
}
function createGrid(numberOfRows) {
resetColorOfBoxes()
let gridTemplateColumns = 'repeat('+numberOfRows+', 1fr)'
var container = document.getElementById("container");
container.style.gridTemplateColumns = gridTemplateColumns;
container.style.gridTemplateRows = gridTemplateColumns;
let brightness = [];
let i = 0;
let numberOfBoxes = numberOfRows**2;
/*Create boxes*/
for (i; i < numberOfBoxes ; i++) {
brightness[i+1] = 1;
console.log(brightness);
var div = document.createElement("div");
div.classList.add(i+1);
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function () {
var className = this.className;
brightness[className] = brightness[className] - 0.1;
console.log(brightness[className]);
randomRgb(brightness[className]);
this.style.backgroundColor = col;
});
}
}
let btn = document.getElementById("start")
btn.addEventListener("click", promptEntry)
</script>
</html>
I am trying to create 5 images in 5 different places inside my div#leftside. I do create 5 images, but they are in the same position and are not randomly spread inside my div. Here is a code... Can someone help?
<!DOCTYPE html>
<html lang="en">
<head http-equiv="content-type" content="text/html; charset=utf-8">
<title>Matching game</title>
<style type="text/css">
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script type="text/javascript">
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
if (i < 5){
numberOfFaces = document.createElement("img");
i++;
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}
}
</script>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
You were using an if statement when you intended a while loop. Also, you needed to move the positioning logic into the loop.
https://jsfiddle.net/knwL2bn4/
Refactor:
<!DOCTYPE html>
<html lang="en">
<head http-equiv="content-type" content="text/html; charset=utf-8">
<title>Matching game</title>
<style type="text/css">
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script type="text/javascript">
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
while (i < 5){
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
numberOfFaces = document.createElement("img");
i++;
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}
}
</script>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
You should use for loop
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i;
for (i = 0; i < 5; i += 1) {
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
numberOfFaces = document.createElement("img");
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}
}
Not quite sure what you are trying to do there, but I rewrote it in a Fiddle. You might have to tweak it to get it to do what you want:
Fiddle
HTML
<body>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
Javascript
function generateFaces() {
var face;
var theLeftSide = document.getElementById("leftSide");
for (i = 0; i < 5; i++) {
var topvar = (Math.floor(Math.random() * 400));
var leftvar = (Math.floor(Math.random() * 400));
face = document.createElement("img");
face.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
face.style.top = topvar + 'px';
face.style.left = leftvar + 'px';
theLeftSide.appendChild(face);
}
}
generateFaces();
CSS
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
I'm using a Webview in my android app. I'm placing a 2d canvas over a webgl canvas (webgl commented out here). Now, when I start up the app, half the time it draws the expected path, and half the time it draws nothing. Am I missing something? Could this be a caching problem or something?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cardboard container</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
margin: 0px;
overflow: hidden;
/*background-color: black;*/
}
#container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
display: none;
}
#stamp {
position: absolute;
top: 0px;
left: 160px;
width: 38px;
height: 38px;
background-color: red;
z-index: 0;
}
#bezier{
z-index: 2;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="stamp"></div>
<canvas id="bezier">Error creating bezier canvas</canvas>
<script src="js/third-party/threejs/three.js"></script>
<script src="js/third-party/threejs/StereoEffect.js"></script>
<script src="js/webgl.js"></script>
<script src="js/bezier.js"></script>
<script>
var consecutiveAbsentFrames = 6;
var totalFrames = 90;
var frameCount = 0;
var straightLineSpeed = 0.05;
var scaleFactor = 0.9;
var numGridPoints = 196;
var fovRadius = 9;
var fovXoffset = 0.5;
var gridPoints = []; // Points are an array [x0,y0,x1,y1,...]
var gridPoints2d = [];
var completePath = [];
var pathIndex = 0;
init();
function init() {
stamp = document.getElementById('stamp');
init2d();
}
function init2d(){
var b = document.getElementById('bezier');
b.width = window.innerWidth * scaleFactor * 0.5;
b.height = window.innerHeight;
var ctx=b.getContext('2d');
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();
}
</script>
</body>
</html>
EDIT:
Behavior is normal on a Moto X with Android 5.1, incorrect on Note 5 with 5.1.1
I suck at math so I cannot figure out what is required to make the zooming work properly. You see, when clicked for the first time, it works as intended (it zooms in to the desired position). But if you try to click more than once it won't zoom in to the desired position.
Here's the code (also provided at http://jsfiddle.net/XVmNU/)
<!DOCTYPE HTML>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
(function ($) {
var scale = 1;
$(window).load(function () {
$('img:first').click(function (e) {
scale *= 1.5;
var w = $(this).width(),
h = $(this).height();
var new_w = w * scale,
new_h = h * scale;
var x = e.pageX,
y = e.pageY;
var new_x = Math.round(x / (w / new_w)),
new_y = Math.round(y / (h / new_h));
new_x = (0 - (new_x - x)),
new_y = (0 - (new_y - y));
$(this).animate({
left: new_x,
top: new_y,
width : new_w,
height : new_h
}, 'fast');
});
});
})(jQuery);
</script>
</head>
<body>
<img src="http://www.worldpress.org/images/maps/world_600w.jpg" style="position: absolute; left: 0px; top: 0px;"/>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
(function ($) {
var scale = 1;
$(window).load(function () {
$('img:first').click(function (e) {
scale *= 1.5;
var w = $(this).width(),
h = $(this).height();
var new_w = w * scale,
new_h = h * scale;
var x = e.pageX,
y = e.pageY;
var new_x=Math.round([x-($(this).position().left)]*(1-scale)+$(this).position().left),
new_y=Math.round([y-($(this).position().top)]*(1-scale)+$(this).position().top);
$(this).animate({
left: new_x,
top: new_y,
width : new_w,
height : new_h
}, 'fast');
});
});
})(jQuery);
</script>
</head>
<body>
<img src="http://www.worldpress.org/images/maps/world_600w.jpg" style="position: absolute; left: 0px; top: 0px;"/>
</body>
</html>
is is something wrong with your method to compute the new_x and new_y.