How can I draw JavaScript graphical elements on top of custom image? - javascript

I have some Javascript drawing random square elements in the DOM. I have a gif (Image) I want these elements to appear over but they keep appearing underneath the gif. I tried defining z-depth and layout parameters to move these elements on top of the image here, but this produced no difference.
Any assistance in achieving the result (drawing elements onclick, on top of this gif) would be much appreciated.
I ultimately want to draw various other images over this image onclick, restricted to this particular area on top of the gif. If someone can suggest a solution to this as well I would be very much grateful!
(Code features some unused elements from my past attempts)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="div.css" />
</head>
<body>
<div style="cursor: pointer;" id="boxy" >
<img src="bg.gif" alt="unfinished bingo card" onclick="create()" />
</div>
</div>
<script>
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.height = 1300;
canvas.width = 1300;
var context = canvas.getContext("2d");
body.appendChild(canvas);
var rects = [];
function create() {
// Opacity
context.globalAlpha = 0.7;
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = color;
//Each rectangle's size is (20 ~ 100, 20 ~ 100)
var coordx = Math.random() * canvas.width;
var coordy = Math.random() * canvas.width;
var width = Math.random() * 80 + 20;
var height = Math.random() * 80 + 20;
var rect = {
x: coordx,
y: coordy,
w: width,
h: height
}
var ok = true;
rects.forEach(function (item) {
if (isCollide(rect, item)) {
console.log("collide");
ok = false;
} else {
console.log("no collision");
}
})
if (ok) {
context.fillRect(coordx, coordy, width, height);
rects.push(rect);
} else {
console.log('rect dropped');
}
console.log(rects);
}
function isCollide(a, b) {
return !(
((a.y + a.h) < (b.y)) ||
(a.y > (b.y + b.h)) ||
((a.x + a.w) < b.x) ||
(a.x > (b.x + b.w))
);
}
document.getElementById('boxy').addEventListener('click', create);
document.getElementById('canvas').style.position = "relative";
document.getElementById('canvas').style.zIndex = "10";
</script>
</body>
</html>
#my-div {
width: 1300x;
height: 1300px;
z-index: -1;
}
a.fill-div {
display: block;
height: 100%;
width: 100%;
text-decoration: none;
}
#boxy {
display: inline-block;
height: 100%;
width: 100%;
text-decoration: none;
z-index: -1;
}
.canvas {
display: inline-block;
height: 100%;
width: 100%;
text-decoration: none;
z-index: 10;
}

You have to use position:absolute; to take it out of the html flow.
Now anything added after the image will be placed like the image was never there.
img {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: -10;
}
div {
font-size: 2rem;
color: white;
}
<img src="https://images.unsplash.com/photo-1664273107076-b6d1fbfb973b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1171&q=80">
<div>Hello i am on top of the image
</div>

Related

How to auto generate divs with javascript?

I made a basic javascript code so you can poke divs with you mouse.
Unfortunately I have to add them manualy but i wanna add so much of them with a pattern.
First i decided to use grid but i guessed it wont work because divs (which i call them squares from now on :D) can change their position.
So I was about to ask, how can I create a javascript code that i can spawn them until they fill the screen.
Also i have another question which is realted to this project, How can i make these squares just decors. I mean by decors i dont want them to effect the webside at all, when the blocks goes out of the screen the body starts to expend, is there any way to avoid that?
(Also it will be better if you make the snippet full screen!)
EDIT: I put the refresh-button on the top left on the main div so you can draw squares by clicking it!
let mouse = {
speedX: 0,
speedY: 0,
posX: 0,
posY: 0,
movement: 0,
speed: 0
}
//on mousemove update the moouse object
document.onmousemove = function(e) {
mouse.speedX = e.movementX;
mouse.speedY = e.movementY
mouse.posX = e.pageX;
mouse.posY = e.pageY;
}
//refresh the mouse movement and speed every 100ms
setInterval(() => {
mouse.movement =
Math.sqrt(Math.pow(mouse.speedX, 2) + Math.pow(mouse.speedY, 2));
mouse.speed = mouse.movement * 10;
}, 100);
//add a square div in parent element
function addSquare(parent) {
const newDiv = document.createElement("div");
newDiv.classList.add("square")
parent.appendChild(newDiv)
return newDiv;
}
//add squares in the parent element filling the available size
//gap is the space between squares, size is the edge of the square
//if skipbefore is false it will begin to draw the next square also if it won't fit entirely
function addSquares(parent, gap, size, skipbefore = true) {
const squares = [];
let rect = parent.getBoundingClientRect();
const availableWidth = rect.width;
const availableHeight = rect.height;
let top = 100;
while (top < availableHeight) {
let left = 0;
if (skipbefore && top + size > availableHeight)
break;
while (left < availableWidth) {
if (skipbefore && left + size > availableWidth)
break;
const square = addSquare(parent);
square.style.left = `${left}px`;
square.style.top = `${top}px`;
squares.push(square);
left += gap + size;
}
top += gap + size;
}
return squares;
}
//onmoveover event handler
const squareOnMouseOver = (event) => {
const element = event.target;
const y = mouse.speedY;
const x = mouse.speedX;
const rad = Math.atan2(y, x);
yAxis = mouse.movement * Math.sin(rad);
xAxis = mouse.movement * Math.cos(rad);
const rect = element.getBoundingClientRect();
const left = Math.round(rect.x + xAxis * 3);
const top = Math.round(rect.y + yAxis * 3);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
const o = rad * (180 / Math.PI);
element.style.transform = `rotate(${o}deg)`;
}
//resets the .target parent and redraw the squares inside it
function drawSquares() {
const parent = document.querySelector('.target');
parent.innerHTML = '';
const squares = addSquares(parent, 25, 75);
const colors = [
'lightcoral',
'bisque',
'aquamarine',
'cadetblue',
'greenyellow',
'yellowgreen'
];
squares.forEach(square => {
const iColor = Math.floor(Math.random() * (colors.length - 1));
const color = colors[iColor];
square.style.background = color;
square.addEventListener('mouseover', squareOnMouseOver);
});
}
body{
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: rgb(242, 239, 231);
color: rgb(10, 10, 9);
}
.square{
background-color: lightcoral;
width: 75px;
height: 75px;
position: absolute;
transform: rotate(0deg);
transition: all ease-out 0.5s;
}
.background {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.container .row .col > * {
display: inline-block;
}
.target {
display: block;
width: 100%;
height: 100%;
}
#draw {
font-size: 20px;
padding: .2em 1em;
cursor: pointer;
}
.name{
font-size: 40px;
}
#main-container{
position: absolute;
padding: 35px 45px;
width: 950px;
height: 285px;
box-shadow: 0px 2px 5px 2px rgb(191, 188, 182);
}
.links{
display: flex;
justify-content: center;
align-items: center;
}
.icons{
width: 55px;
height: auto;
margin: 0px 25px;
padding: 10px;
border-radius: 5px;
transition: all ease-in 0.2s;
}
.icons:hover{
background-color: rgb(144, 144, 144);
}
.refresh{
position: absolute;
}
.refresh-button{
width: 25px;
height: auto;
}
.btn:hover{
background-color: rgb(144, 144, 144);
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="css.css">
<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>Document</title>
</head>
<body>
<div class="background">
<div class="target"></div>
<div class="container text-center" id="main-container">
<div class="">
<div class="refresh">
<button class="btn" id="draw" onclick="drawSquares()"><img class="refresh-button" src="SVG/arrow-clockwise.svg"></button>
</div>
<div class="name">Berk Efe Keskin</div>
<br>
<i>This website is working in progress right now...</i>
<br>
<i>Here is some useful links.</i>
<br>
<br>
<div class="links">
<img class="icons" src="SVG/github.svg">
<img class="icons" src="SVG/linkedin.svg">
<img class="icons" src="SVG/stack-overflow.svg">
</div>
</div>
</div>
</div>
<script type="text/javascript" src = "javascript.js"></script>
</body>
</html>
You may have a function that given a container will be filled with how many squares can fit inside as long as there is still avaiable width and available height in the target.
Here in this demo I better factored your code and added a main function called drawSquares that gets called when the button reDRAW is clicked. Each time the squares are redrawn, the target content is emptied.
I'm using a button to trigger the box drawing because the available space depends on the size of the area when the action is fired. For example you can expand the snippet and decide to redraw the squares to have the whole new area filled again.
You may decide to call the action on document ready or when the window gets resized.
let mouse = {
speedX: 0,
speedY: 0,
posX: 0,
posY: 0,
movement: 0,
speed: 0
}
//on mousemove update the moouse object
document.onmousemove = function(e) {
mouse.speedX = e.movementX;
mouse.speedY = e.movementY
mouse.posX = e.pageX;
mouse.posY = e.pageY;
}
//refresh the mouse movement and speed every 100ms
setInterval(() => {
mouse.movement =
Math.sqrt(Math.pow(mouse.speedX, 2) + Math.pow(mouse.speedY, 2));
mouse.speed = mouse.movement * 10;
}, 100);
//add a square div in parent element
function addSquare(parent) {
const newDiv = document.createElement("div");
newDiv.classList.add("square")
parent.appendChild(newDiv)
return newDiv;
}
//add squares in the parent element filling the available size
//gap is the space between squares, size is the edge of the square
//if skipbefore is false it will begin to draw the next square also if it won't fit entirely
function addSquares(parent, gap, size, skipbefore = true) {
const squares = [];
let rect = parent.getBoundingClientRect();
const availableWidth = rect.width;
const availableHeight = rect.height;
let top = 100;
while (top < availableHeight) {
let left = 0;
if (skipbefore && top + size > availableHeight)
break;
while (left < availableWidth) {
if (skipbefore && left + size > availableWidth)
break;
const square = addSquare(parent);
square.style.left = `${left}px`;
square.style.top = `${top}px`;
squares.push(square);
left += gap + size;
}
top += gap + size;
}
return squares;
}
//onmoveover event handler
const squareOnMouseOver = (event) => {
const element = event.target;
const y = mouse.speedY;
const x = mouse.speedX;
const rad = Math.atan2(y, x);
yAxis = mouse.movement * Math.sin(rad);
xAxis = mouse.movement * Math.cos(rad);
const rect = element.getBoundingClientRect();
const left = Math.round(rect.x + xAxis * 3);
const top = Math.round(rect.y + yAxis * 3);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
const o = rad * (180 / Math.PI);
element.style.transform = `rotate(${o}deg)`;
}
//resets the .target parent and redraw the squares inside it
function drawSquares() {
const parent = document.querySelector('.target');
parent.innerHTML = '';
const squares = addSquares(parent, 25, 75);
const colors = [
'lightcoral',
'bisque',
'aquamarine',
'cadetblue',
'greenyellow',
'yellowgreen'
];
squares.forEach(square => {
const iColor = Math.floor(Math.random() * (colors.length - 1));
const color = colors[iColor];
square.style.background = color;
square.addEventListener('mouseover', squareOnMouseOver);
});
}
body {
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
}
.square {
background-color: lightcoral;
width: 75px;
height: 75px;
position: absolute;
transform: rotate(0deg);
transition: all ease-out 0.5s;
}
#Header {
font-size: italic;
}
.background {
width: 100%;
height: 100%;
}
.target {
position: relative;
display: block;
width: 100%;
height: 100%;
z-index: -1;
}
#draw {
font-size: 20px;
padding: .2em 1em;
cursor: pointer;
}
.container .row .col > * {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link el="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<body>
<div class="background">
<span>Work in progress...</span>
<div class="container text-center">
<div class="row">
<div class="col">
<h1 id="Header">Work in progress...</h1>
<button id="draw" onclick="drawSquares()">reDRAW</button>
</div>
</div>
</div>
<div class="target"></div>
</div>
</body>

Why is my cursor and my line of draw are in diffrent sides?

I am attempting to create a drawing app in JS, however, whenever anything is drawn, it is positioned away from my cursor depending on where it is on the canvas, when I am on the furthest left/bottom side of the canvas, you can draw where your cursor is, but the further right/up I move, the more the brush begins to "drift" and go further than where my cursor is.
const canvas = document.getElementById("canvas");
const increaseBtn = document.getElementById("increase");
const decreaseBtn = document.getElementById("decrease");
const sizeEl = document.getElementById("size");
const colorEl = document.getElementById("color");
const clearEl = document.getElementById("clear");
//Core Drawing Functionality (with some research)
const ctx = canvas.getContext("2d");
let size = 5;
let isPressed = false;
let color = "black";
let x;
let y;
let fakeSize = 1;
canvas.addEventListener("mousedown", (e) => {
isPressed = true;
x = e.offsetX;
y = e.offsetY;
});
canvas.addEventListener("mouseup", (e) => {
isPressed = false;
x = undefined;
y = undefined;
});
canvas.addEventListener("mousemove", (e) => {
if (isPressed) {
const x2 = e.offsetX;
const y2 = e.offsetY;
drawCircle(x2, y2);
drawLine(x, y, x2, y2);
x = x2;
y = y2;
}
});
function drawCircle(x, y) {
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = color;
ctx.lineWidth = size * 2;
ctx.stroke();
}
function updateSizeOnScreen() {
sizeEl.innerHTML = fakeSize;
}
increaseBtn.addEventListener("click", () => {
size += 5;
fakeSize++;
if (fakeSize > 10) {
fakeSize = 10;
}
if (size > 50) {
size = 50;
}
updateSizeOnScreen();
});
decreaseBtn.addEventListener("click", () => {
size -= 5;
fakeSize--;
if (fakeSize < 1) {
fakeSize = 1;
}
if (size < 5) {
size = 5;
}
updateSizeOnScreen();
});
colorEl.addEventListener("change", (e) => {
color = e.target.value;
});
clearEl.addEventListener("click", () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
//Eraser and Pencil Actions (my own algorithm)
const eraser = document.getElementById("eraser");
const pencil = document.getElementById("pencil");
eraser.addEventListener("click", () => {
localStorage.setItem("colorEl", JSON.stringify(color));
color = "#fff";
colorEl.disabled = true;
canvas.classList.add("eraseractive");
eraser.classList.add("eraseractive");
colorEl.classList.add("eraseractive");
canvas.classList.remove("pencilactive");
eraser.classList.remove("pencilactive");
colorEl.classList.remove("pencilactive");
});
pencil.addEventListener("click", () => {
JSON.parse(localStorage.getItem("colorEl"));
color = colorEl.value;
colorEl.disabled = false;
canvas.classList.remove("eraseractive");
eraser.classList.remove("eraseractive");
colorEl.classList.remove("eraseractive");
canvas.classList.add("pencilactive");
eraser.classList.add("pencilactive");
colorEl.classList.add("pencilactive");
});
// Dark/Light Mode
const darkMode = document.getElementById("darkMode");
const lightMode = document.getElementById("lightMode");
const toolbox = document.getElementById("toolbox");
darkMode.addEventListener("click", () => {
darkMode.classList.add("mode-active");
lightMode.classList.remove("mode-active");
lightMode.classList.add("rotate");
darkMode.classList.remove("rotate");
toolbox.style.backgroundColor = "#293462";
document.body.style.backgroundImage =
"url('/assets/images/darkModeBackground.svg')";
document.body.style.backgroundSize = "1920px 1080px";
canvas.style.borderColor = "#293462";
toolbox.style.borderColor = "#293462";
});
lightMode.addEventListener("click", () => {
lightMode.classList.add("mode-active");
darkMode.classList.remove("mode-active");
darkMode.classList.add("rotate");
lightMode.classList.remove("rotate");
toolbox.style.backgroundColor = "#293462";
document.body.style.backgroundImage =
"url('/assets/images/lightModeBackground.svg')";
document.body.style.backgroundSize = "1920px 1080px";
canvas.style.borderColor = "#293462";
toolbox.style.borderColor = "#293462";
});
* {
box-sizing: border-box;
font-size: 20px !important;
}
body {
background: url("https://drawing-app-green.vercel.app/assets/images/lightModeBackground.svg");
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
margin: 0;
position: relative;
max-height: 100vh;
overflow: hidden;
}
::selection {
background: transparent;
}
::-moz-selection {
background: transparent;
}
.mode {
display: flex;
position: absolute;
top: 10px;
right: 25px;
cursor: pointer;
}
.light-mode {
color: yellow;
}
.dark-mode {
color: #16213e;
}
.container {
display: flex;
flex-direction: column;
max-width: 1200px;
width: 100%;
max-height: 600px;
height: 100%;
}
canvas {
display: flex;
border: 2px solid #293462;
cursor: url("https://drawing-app-green.vercel.app/assets/images/pencilCursor.png") 2 48, pointer;
background-color: #fff;
margin-top: 3rem;
width: 100%;
height: 600px;
}
.toolbox {
background-color: #293462;
border: 1px solid #293462;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
padding: 0.2rem;
}
.toolbox > * {
background-color: #fff;
border: none;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 2rem;
height: 30px;
width: 30px;
margin: 0.25rem;
padding: 0.25rem;
cursor: pointer;
}
.toolbox > *:last-child {
margin-left: auto;
}
canvas.eraseractive {
cursor: url("https://drawing-app-green.vercel.app/assets/images/eraserCursor.png") 2 48, pointer;
}
#color.eraseractive {
cursor: not-allowed;
}
canvas.pencilactive {
cursor: url("https://drawing-app-green.vercel.app/assets/images/pencilCursor.png") 2 48, pointer;
}
.mode-active {
visibility: hidden;
}
.rotate {
transform: rotate(360deg);
transition: transform 1s linear;
}
<!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>Drawing App</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
</head>
<body>
<i class="fa-solid fa-moon dark-mode fa-2x mode" id="darkMode"></i>
<i
class="fa-solid fa-sun light-mode fa-2x mode mode-active"
id="lightMode"
></i>
<div class="container">
<canvas id="canvas" width="1024" height="600"></canvas>
<div class="toolbox" id="toolbox">
<button id="decrease">-</button>
<span id="size">1</span>
<button id="increase">+</button>
<input type="color" id="color" />
<button id="pencil">
<img src="assets/images/pencilCursor.png" alt="" />
</button>
<button id="eraser">
<img src="assets/images/eraserCursor.png" alt="" />
</button>
<button id="clear">X</button>
</div>
</div>
<script src="assets/js/script.js"></script>
</body>
</html>
Your problem is that your canvas dimentions don't match with the dimentions of the HTML element that contains it. You see: your canvas has a fixed width="" and height="" attributes set. But in your HTML your canvas element has a width of 100%. So that means that the container vairies in dimentions but the canvas inside it not. This result in the canvas trying to resize to show inside the container thus giving you issues with calculating exacly what pixel you are clicking.
You have two options:
Option 1: calculate your click position taking into account canvas deformation
If you want your canvas to resize, then calculate the real position using a simple ratio formula. If for example your canvas has a width of 100 but right now its container is 10px wide, then if you click on pixel 5 you expect a dot to be drawn at pixel 50. In other words if your canvas is smaller by a factor of 10 then you need to multiply your position by a factor of 10.
In your code it would look something like this:
// this is your same code in lines 33 ana34 but see that I added a multiplication by the ratio between the canvas size and the canvas container
const x2 = e.offsetX * (canvas.width / ctx.canvas.getBoundingClientRect().width);
const y2 = e.offsetY * (canvas.height / ctx.canvas.getBoundingClientRect().height);
Option #2: Dont allow your canvas to deform
Remove the container class, and remove the width:100% from your canvas css. Your canvas will overflow and cause a scrollbar but the positions will be calculated properly with your code.

Animation slowing down

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.

Resize and rearrange divs through drag & drop and dynamic CSS

I have two divs that I want my users to be able to hit a button and arrange these two divs top/down or left/right. I have implemented it but whenever I arrange them left/right, the right div often overflows to the bottom of the left div.
I have seen another similar example that talks about resizing left/right divs, but I still don't know what exactly caused my right div to overflow. Any help is appreciated!
Here is my example:
var d = $('#divider'); // divider between top and bottom divs
var t = $('#tl'); // top/left div
var b = $('#br'); // bottom/right div
var h = $('body').height();
var w = $('body').width();
var isDragging = false;
var isLandscape = false;
d.mousedown(function(e) {
isDragging = true;
});
$(document).mouseup(function() {
isDragging = false;
}).mousemove(function(e) {
if (isDragging) {
if (!isLandscape) {
t.css('height', e.pageY);
b.css('height', h - e.pageY - d.height());
d.css('height', h - t.height() - b.height());
} else {
t.css('width', e.pageX);
b.css('width', w - e.pageX - d.width());
d.css('width', w - t.width() - b.width());
}
}
});
var rotateBtn = document.getElementById('rotateScreen');
if (rotateBtn) {
rotateBtn.addEventListener('click', rotateDisplay, false);
} else {
throw error;
}
function rotateDisplay() {
if (!isLandscape) {
isLandscape = true;
t.css('height', h);
t.css('width', Math.round(0.75 * w));
b.css('height', h);
b.css('width', Math.round(0.24 * w));
d.css('height', h);
d.css('width', w - t.width() - b.width());
d.css('cursor', 'w-resize');
} else {
isLandscape = false;
t.css('height', Math.round(0.75 * h));
t.css('width', w);
t.css('float', 'left');
b.css('height', Math.round(0.24 * h));
b.css('width', w);
b.css('float', 'left');
d.css('height', h - t.height() - b.height());
d.css('width', w);
d.css('cursor', 'n-resize');
d.css('float', 'left');
}
}
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#br {
width: 100%;
height: 24%;
float: left;
background: gold;
}
#tl {
width: 100%;
height: 75%;
float: left;
background: navy;
}
#divider {
height: 1%;
background: #fff;
float: left;
width: 100%;
cursor: ns-resize;
}
#control {
position: absolute;
z-index: 5;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="control">
<button id="rotateScreen">🔁</button>
</div>
<div id="tl">This is the top/left div</div>
<div id="divider"></div>
<div id="br">This is the bottom/right div</div>

multiple canvas as buttons with onclick event

I'm having really big problems with canvas code that I'm using only 1 time in the page (in logo) working fine, and that I'm trying to use it as buttons for menu and here is the problem, I don't know really what's im doing wrong, hope some of u help me.
it's the code that I'm using for the logo and is working fine:
HTML CODE:
<html>
<head>
<title>canvas</title>
</head>
<body>
<div id="container">
<div id="logo">
<canvas style="" width="800" id="broken-glass"></canvas>
<h1 style="color: rgba(250, 250, 250, 0.95);" id="logo-title">Canvas</h1>
</div>
<script type="text/javascript">
(function() {
var isCanvasSupported = function () {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
if( isCanvasSupported() ) {
var canvas = document.getElementById('broken-glass'),
context = canvas.getContext('2d'),
width = canvas.width = Math.min(800, window.innerWidth),
height = canvas.height,
numTriangles = 100,
rand = function(min, max){
return Math.floor( (Math.random() * (max - min + 1) ) + min);
};
window.drawTriangles = function(){
context.clearRect(0, 0, width, height);
var hue = rand(0,360);
var increment = 80 / numTriangles;
for(var i = 0; i < numTriangles; i++) {
context.beginPath();
context.moveTo(rand(0,width), rand(0,height) );
context.lineTo(rand(0,width), rand(0,height) );
context.lineTo(rand(0,width), rand(0,height) );
context.globalAlpha = 0.5;
context.fillStyle = 'hsl('+Math.round(hue)+', '+rand(15,60)+'%, '+ rand(10, 60) +'%)';
context.closePath();
context.fill();
hue+=increment;
if(hue > 360) hue = 0;
}
canvas.style.cssText = '-webkit-filter: contrast(115%);';
};
document.getElementById('logo-title').style.color = 'rgba(250, 250, 250, 0.95)';
drawTriangles();
var el = document.getElementById('logo');
el.onclick = function() {
drawTriangles();
};
}
})();
</script>
</div>
</body>
</html>
and it's CSS CODE:
#broken-glass
{
position: absolute;
left: 0px;
top: 0px;
width: 100%;
}
#logo h1
{
text-align: center;
font-weight: 700;
width: 100%;
color: #000;
position: absolute;
left: 0px;
-moz-user-select: none;
cursor: pointer;
margin-top: 27px;
font-size: 63px;
line-height: 1.4;
top: 0px;
margin-bottom: 5px;
text-rendering: optimizelegibility;
font-family: Calibri,"PT Sans","Trebuchet MS","Helvetica Neue",Arial;
}
the big problem comes when i change the id's (#) to classes (.) and the "id" tag to "class" tag in the html, the canvas is overlapped... the text of h1 tag is out of the canvas... and just the hell of problems, can someone tell me what I'm doing wrong?, how to fix it, I'm trying it during hours...
too much thanks in advance!.
you may try putting an !important in every code in your css.
example:
text-align: center !important;
font-weight: 700 !important;
this fixed my problem before, hopefully it will fix yours also.

Categories

Resources