how to add interval clock to a random square generator - javascript

i'm trying to make a random square generator that makes one square show up on the screen every 5 seconds (not an additional square but i'm trying to move the original square to a random location every 5 seconds)
i experimented with interval but nothing worked.
this is what i done so far. it gives me a random square every time i refresh the page.
var h = window.innerHeight;
var w = window.innerWidth;
var randomTop = Math.random() * h;
var randomLeft = Math.random() * w;
var boxPosition = {
left: randomLeft,
top: randomTop
};
document.write('<div style="width: 64px; height:64px;background-color:blue; left: ' + boxPosition.left + 'px; top: ' + boxPosition.top + 'px;position: absolute"></div>');
https://codepen.io/danielle-23523/pen/LYRpPNp

If you wrap your code in a function and call that function on load as well as in setInterval it works.
I also updated your code to delete any previously added boxes.
var h = window.innerHeight;
var w = window.innerWidth;
function create() {
var boxPosition = {
left: Math.random() * w,
top: Math.random() * h
};
box = document.querySelector("#box")
if(box)box.remove();
document.write(
'<div id="box" style="width: 64px; height:64px;background-color:blue; left: ' +
boxPosition.left +
"px; top: " +
boxPosition.top +
'px;position: absolute"></div>'
);
}
create();
setInterval(create, 5000);

Try this:-
<html>
<head>
</head>
<body>
<script>
function generateAndAddSquare() {
var h = window.innerHeight;
var w = window.innerWidth;
var randomTop = Math.random() * h;
var randomLeft = Math.random() * w;
var boxPosition = {
left: randomLeft,
top: randomTop
};
var node = document.createElement('div')
node.style.width = '64px';
node.style.height = '64px';
node.style.backgroundColor = 'blue';
node.style.left = boxPosition.left + 'px';
node.style.top = boxPosition.top + 'px';
node.style.position = 'absolute';
document.body.appendChild(node);
}
setInterval(generateAndAddSquare, 1000);
</script>
</body>
</html>

Related

How to set css width or left attributes to get pixel perfect result?

I just started experimenting with JS/CSS a bit and I came across this problem I couldn't find an answer for on the forum.
I wonder how I could get rid off the white line in the middle of the window (picture attached). It doesn't appear all the time but at certain scalings.
Many thanks
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
}
.d {
position: fixed;
margin: 0;
padding: 0;
border: 0px;
background-color: #A1F1F1;
text-align: center;
}
</style>
</head>
<body>
<script>
var numOfDivsHor = 10;
var numOfDivsVer = 10;
function setCubeSize() {
document.body.innerHTML = '';
var w = document.body.clientWidth;
var h = document.body.clientHeight;
var fs = h/numOfDivsVer/3;
for (i=0; i < numOfDivsHor; i++) {
for (j=0; j < numOfDivsVer; j++) {
var d = document.createElement('div');
document.getElementsByTagName('body')[0].appendChild(d);
d.id = i + '' + j;
d.className = 'd';
d.innerHTML = i + '' + j;
setLayout(i + '' + j, w, h, fs);
d.style.left = j * w/numOfDivsHor + 'px';
d.style.top = i * h/numOfDivsVer + 'px';
d.style.backgroundColor = 'rgb(120, ' + Math.round(i * 25.5) + ', ' + Math.round(j * 25.5) + ')';
}
}
}
function setLayout(divId, w, h, fs) {
var d = document.getElementById(divId);
d.style.width = 100/numOfDivsHor + '%';
d.style.height = 100/numOfDivsVer + '%';
d.style.fontSize = fs + 'px';
d.style.paddingTop = (h/numOfDivsVer - fs)/2 + 'px';
}
document.addEventListener('DOMContentLoaded', function() {;
setCubeSize();
});
window.addEventListener('resize', function() {
setCubeSize();
});
</script>
</body>
</html>
white line in the middle
This a rounding issue that is common when dealing with graphics and floating point numbers. You more or less just need to floor values when you divide.
Specifically, this change fixes the problem in the code that you posted. Change:
d.style.left = j * w/numOfDivsHor + 'px';
d.style.top = i * h/numOfDivsVer + 'px';
to:
d.style.left = j * Math.floor(w/numOfDivsHor) + 'px';
d.style.top = i * Math.floor(h/numOfDivsVer) + 'px';
Note that you will be left with whitespace on one edge of the grid. This is because the size of the window is not a perfect multiple of the size of a cell. You have to choose either between keeping the sizes of the cells the same, as above, or having varying sizes of cell, which would take a bit more work.

Place elements to canvas using JavaScript

I'm making a little game. I will place some div-tags into a canvas-tag by JavaScript. This is my code:
document.addEventListener("DOMContentLoaded", function () {
init();
});
function init(){
draw();
}
function draw(){
var number = Math.round((Math.random() * 31) + 20);
var cnv = document.getElementsByTagName("canvas")[0];
for (i = 0; i <= number ; i++){
var div = document.createElement('div');
//breedte
var length = Math.round((Math.random() * 31) + 20);
div.style.height = length + "px";
div.style.width = length + "px";
//locattie
div.style.top = Math.floor(Math.random() * (cnv.height - 100))+ "px";
div.style.left = Math.floor(Math.random() * (cnv.width - 100))+ "px";
//toevoegen
div.style.backgroundColor = "rgb(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ")";
cnv.appendChild(div);
}
}
canvas{
width: 100%;
height: 500px;
background-color: #898989;
}
div {
position: absolute;
}
<canvas id="playarea">
</canvas>
So you can see, it displays only a empty canvas. Only if I implement the element, I can see the generated div-tags. I have also try it replace some properties in the CSS code of my div. But it don't work...
Can anyone help me? Thanks
canvas isn't intended to encapsulate div-s like this. You should try to use native canvas methods like fillRect() for example, see this MDN tutorial
With a quick example:
document.addEventListener("DOMContentLoaded", function () {
init();
});
function init(){
draw();
}
function draw(){
var number = Math.round((Math.random() * 31) + 20);
var cnv = document.getElementsByTagName("canvas")[0];
var ctx = cnv.getContext("2d");
var top = 0;
var left = 0;
var size = 0;
for (i = 0; i <= number ; i++){
ctx.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ")";
top = Math.floor(Math.random() * (cnv.height - 100));
left = Math.floor(Math.random() * (cnv.width - 100));
size = Math.round((Math.random() * 31) + 20);
ctx.fillRect(left, top, size, size);
}
}
Nodes inside a canvas object will only be shown in browsers that doesn't support the canvas element:
<canvas>Your browser <em>doesn't</em> support the canvas element!</canvas>
If you want to add elements on top of your canvas you could consider adding a wrapper and add the elements to it:
<div class="canvas_wrapper">
<canvas></canvas>
<div class="canvas_child">My added element</div>
</div>
And some css like this:
.canvas_wrapper { position: relative; }
.canvas_child { position: absolute; top: 100px; left: 100px; }

Changing a div attribute using a function?

I am not sure why my move function, is not changing the style.left or style.top attributes of my 'toy'
Any tips, or general information/links on how to animate a div? I'm pulling my hair out over here. :)
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
//var moveX = math.random() * velocity;
//var moveY = math.random() * velocity;
function init() {
alert("in init fucntion");
ref = document.getElementById("toy");
alert("ref = " + ref.valueOf());
timer = setInterval(move, 50);
}
function move() {
alert("called move");
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
alert("left = " + left.valueOf() + " top = " + top.valueOf());
left += 5;
top += 5;
alert("left =" + left.valueOf() + "top = " + top.valueOf());
ref.style.left += left;
ref.style.top += 5;
alert("ref.style.left = " + ref.style.left.valueOf() + " ref.style.top = " + ref.style.top.valueOf());
ref.style.left = (left + deltaX) % posEnd;
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
You just need to specify the units the position is in. For example, style.left = 10 won't work - you need style.left = '10px';
Here is a slightly simplified version of your move() function showing this:
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
And a fully working snippet:
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
function init() {
ref = document.getElementById("toy");
timer = setInterval(move, 500);
}
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
</body>
</html>

Why are my event listeners only working for the last element?

The problem is that when I drag/drop a picture, it always gets put on the last letter.
Here's an image of what I am talking about:
Here is my code:
function mattes_draw_letter(x, y, width, height, letter, position)
{
var canvas = document.createElement('canvas');
canvas.style.position = "absolute";
canvas.style.top = 0 + "px";
canvas.id = "canvas_opening_" + position;
canvas.style.zIndex = 5;
var ctx = canvas.getContext("2d");
ctx.lineWidth = 1;
ctx.fillStyle = '#bfbfbf';
ctx.strokeStyle = '#000000';
ctx.beginPath();
ctx.moveTo(x + letter[0] * width, y + letter[1] * height);
for (i = 0; i < letter.length; i+=2)
{
if (typeof letter[i+3] !== 'undefined')
{
ctx.lineTo(x + letter[i+2] * width, y + letter[i+3] * height);
}
}
ctx.fill();
ctx.stroke();
ctx.closePath();
$("#mattes").append(canvas);
canvas.addEventListener("drop", function(event) {drop(event, this);}, false);
canvas.addEventListener("dragover", function(event) {allowDrop(event);}, false);
canvas.addEventListener("click", function() {photos_add_selected_fid(this);}, false);
}
Here is the code that has the for loop:
function mattes_create_openings(openings)
{
var opening_array = new Array();
var x = 0;
var y = 0;
var opening_width = 0;
var opening_height = 0;
$(openings).each(function(i, el) {
x = $(el).find("x").text() * ppi;
y = $(el).find("y").text() * ppi;
opening_width = $(el).find("width").text() * ppi;
opening_height = $(el).find("height").text() * ppi;
var type = $(el).find("type").text();
var text = $(el).find("text").text();
var ellipse = (type == "ellipse") ? " border-radius: 50% " : "";
if ("letter" == type)
{
var letter = mattes_get_letter_array(text);
var letter_width = (opening_width - (text.length * 0.5 * ppi)) / text.length;
var space = 0.5 * ppi;
var letterX = x;
var letterY = y;
var letter_height = opening_height;
mattes_draw_letter(letterX, letterY, letter_width, letter_height, letter, i);
letterX += (space + letter_width);
}
else
{
$("#mattes").append("<div id='opening_" + i + "' style='background-color: #bfbfbf; position: absolute; left: " + x + "px; top: " + y + "px; height: " + opening_height + "px; width: " + opening_width + "px; overflow: hidden; z-index: 4;" + ellipse + "' ondrop='drop(event, this)' ondragover='allowDrop(event)' onclick='photos_add_selected_fid(this);'> </div>");
}
//TODO multiple openings max/min -x,y,width, height
opening_array["x"] = x;
opening_array["y"] = y;
opening_array["opening_width"] = opening_width;
opening_array["opening_height"] = opening_height;
});
return opening_array;
}
You need to wrap your code inside $.each in a function call, like this:
$(openings).each(function(i, el) {
bindEvents(i, el);
};
function bindEvents(indx, ele) {
// Code what you have written inside $.each originally
};
The problem was not the event handlers, but the size of the canvas. The last canvas created was on top of the others so it was the only event that was being activated.

"parseInt from form" and "clearing canvas on start()"

Greeting Everyone,
I already asked for some help with this assignment but the help I got was rather fruitless..
hope this time some1 would be to assist me :( ..
I have to draw on an id'd canvas everytime i click on a button,
however after some modification I get the result on my screen but I lost some functionalties,
parsing integer wont work since I get an error:
Uncaught ReferenceError: pGame is not defined
Although it is identified and it used to work at an early stage.
another issue is clearing the canvas everytime I click start:
function start()
{
//tried making a counter, if its the first time to click
//start then do nothing else restore
// context.restore();
if (shouldClear==0) {
setInterval(rotateShape, 30);
var degrees = 0.0;
shouldClear = 1;
}
else{
rotateShape();
shouldClear-1;
}
}
For reference pursposes here is my full code:
<!DOCTYPE HTML>
<html>
<head><title>Rectangles</title></head>
<body>
<script>
var i = 0;
var rectArrayStartX,rectArrayStartY,rectArrayDimY, rectArrayDimX;
var RotatingRectangle = function(x, y, width, height, rot, r,g,b){
var rotation = rot;
var rotationState = 0;
this.draw = function(ctx){
rotationState += rotation;
ctx.save();
ctx.translate(x+(width/2), y+(height/2));
ctx.rotate(rotationState);
var randomRed = Math.floor( Math.random() * 256 );
var randomGreen = Math.floor( Math.random() * 256 );
var randomBlue = Math.floor( Math.random() * 256 );
ctx.fillStyle = "rgb(" + randomRed + ", " + randomGreen + ", " + randomBlue +")";
ctx.fillRect(0-(width/2), 0-(height/2), width, height);
ctx.restore();
}
}
var shouldClear = 0;
function start()
{
//tried making a counter, if its the first time to click
//start then do nothing else restore
// context.restore();
if (shouldClear==0) {
setInterval(rotateShape, 30);
var degrees = 0.0;
shouldClear = 1;
}
else{
rotateShape();
shouldClear-1;
}
}
function construct()
{
var count = 25;
var count = parseInt(pGame.box.value);
var allShapes = [];
for (i=0; i < count; ++i) {
var rotation = Math.random()*.10
var x = Math.floor(Math.random() * 640);
var y = Math.floor(Math.random() * 480);
var randomRed = Math.floor( Math.random() * 256 );
var randomGreen = Math.floor( Math.random() * 256 );
var randomBlue = Math.floor( Math.random() * 256 );
var rect = new RotatingRectangle(x, y, 50, 50, rotation, "rgb(" + randomRed + ", " + randomGreen + ", " + randomBlue +")");
allShapes.push(rect);
}
return allShapes;
}
var allShapes = construct();
function rotateShape()
{
var canvas = document.getElementById('gameId');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 640, 480);
for (i=0; i < allShapes.length; ++i) {
allShapes[i].draw(ctx);
}
if (shouldClear==1) {
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 640, 480);
for (i=0; i < allShapes.length; ++i) {
allShapes[i].draw(ctx);
}
}
}
}
</script>
<div id="rectangles" STYLE = "background-color: #fff68f; width: 600px; height: 420px;
border-style: outset;position: absolute;">
<form name="pGame">
<center>
<b>Canvas Application</b><br>
<input type= "button" value= "Start" onclick= "start()" />
<input id="box" type="text" size="2" value="10" style="border-style:inset;
color:red; background-color: black" />
</center>
</form>
<canvas id="gameId" width="598" height="300"
STYLE = "border:1px solid; background-color: #fff68f; position: absolute;">
</canvas>
</div>
</body>
</html>
The form pGame hasn't been created when you try to access it.
Place your script under the form so that the form will be created before the script is executed or call your script when the DOMContentLoaded event triggers.

Categories

Resources