I'm currently learning JS and I'm doing this canvas exercise, the task is to "draw" circles on a rectangle by the parameters that the user enters (x and y for positioning the first circle, the radius of the circles and the amount of circles), each circle's x should grow by 1 each time and be positioned accordingly.
The thing is I just can't position the circles no matter what I do! I'm pretty sure it's related to my CSS(which I suck at).
Does anyone know how to position the circle at a specific point?
var container = document.getElementById('container');
var rectangle = document.createElement('div');
rectangle.setAttribute('id', 'rectangle');
container.appendChild(rectangle);
var style = document.createElement('style');
style.innerHTML = "#rectangle {height:300px; width: 400px; background-color: #e1c699; position: relative;}";
document.head.appendChild(style);
var formElement = document.createElement('div');
formElement.setAttribute('id', 'form');
var xInput = createInput("x", "Please enter x");
var yInput = createInput("y", "Please enter y");
var radius = createInput("radius", "Please enter radius");
var numOfCircles = createInput("numOfCirc", "Please enter number of circles");
formElement.appendChild(xInput);
formElement.appendChild(yInput);
formElement.appendChild(radius);
formElement.appendChild(numOfCircles);
var submitBtn = createBtn('submit', 'Submit');
formElement.appendChild(submitBtn);
container.appendChild(formElement);
submitBtn.onclick = function() {
var numOfCirc = document.getElementById('numOfCirc').value;
var raidus = document.getElementById('radius').value;
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
for (var i = 1; i <= numOfCirc; i++) {
drawCircle(x, y, raidus, i);
x = parseInt(x) + 1;
}
}
function drawCircle(x, y, raidus, id) {
var circle = document.createElement('div');
circle.setAttribute('class', 'circle');
circle.setAttribute('id', id);
var style = document.getElementsByTagName('style')[0];
if (id == 1) {
var circleSize = ".circle {height: " + radius.value + "px; width: " + radius.value + "px; background-color: #555; border-radius: 50%;}";
var position = "#" + id + " {position: absolute; left: " + x + "px; top: " + y + "px;}"
style.insertAdjacentHTML('beforeend', circleSize);
style.insertAdjacentHTML('beforeend', position);
} else {
var position = "#" + id + " {position: absolute; left: " + x + "px; top: " + y + "px;}"
style.insertAdjacentHTML('beforeend', position);
}
rectangle.appendChild(circle);
}
function createInput(id, displayName) {
var input = document.createElement("input");
input.setAttribute("id", id);
input.setAttribute("placeholder", displayName);
return input;
}
function createBtn(id, displayName) {
var btn = document.createElement("button");
btn.setAttribute("id", id);
btn.innerText = displayName;
return btn;
}
<div id="container">
Also, if you have any general propositions for improvements I'd love to hear them!
Related
I made a random background color generator in HTML/JavaScript. Now, I want to add "Download Background Image" button. But I don't know how.
Here is my code:
function randomBgColor() {
var rmin = +rmintxt.value;
var rmax = +rmaxtxt.value;
var gmin = +gmintxt.value;
var gmax = +gmaxtxt.value;
var bmin = +bmintxt.value;
var bmax = +bmaxtxt.value;
var r = Math.floor(Math.random() * (rmax - rmin + 1) + rmin);
var g = Math.floor(Math.random() * (gmax - gmin + 1) + gmin);
var b = Math.floor(Math.random() * (bmax - bmin + 1) + bmin);
var r2 = Math.floor(Math.random() * 255);
var g2 = Math.floor(Math.random() * 255);
var b2 = Math.floor(Math.random() * 255);
var rhex = r.toString(16);
var ghex = g.toString(16);
var bhex = b.toString(16);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";
var bgColor2 = "rgb(" + r2 + "," + g2 + "," + b2 + ")";
document.body.style.background = bgColor;
rgb.innerHTML = "RGB: " + r + ", " + g + ", " + b;
rgb.style.color = bgColor2.toString(16);
hex.innerHTML = "Hex: #" + rhex.toUpperCase() + ghex.toUpperCase() + bhex.toUpperCase();
hex.style.color = bgColor2.toString(16);
}
I don't know why it doesn't work on StackOverflow, but on my computer it works well. Try to copy-paste and check it out.
var theCanva = document.querySelector('canvas');
var twoD = theCanva.getContext("2d");
var theBtn = document.querySelector('.btn');
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
twoD.width = window.innerWidth;
twoD.height = window.innerHeight;
var link = document.createElement('a');
link.innerHTML = 'Download';
link.addEventListener('click', function(ev) {
link.href = theCanva.toDataURL("image/png");
link.download = "test";
}, false);
theBtn.addEventListener('click', () => {
var color = random_rgba();
twoD.fillStyle = color;
twoD.fillRect(0, 0, 1200, 800);
document.body.appendChild(link);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
canvas {
position: fixed;
width: 100%;
height: 100vh;
z-index: -1;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
<button class="btn">Generate random background color</button>
<canvas></canvas>
If you would like to have the button be able to have a file selector where you could make the page's background be the selected image, then you would need to have a file input, so that you can get the image that the user would like to use as a background to be displayed. In the JS, then you will need to create a variable to get the data of what the chosen file is. Now, you will need to have a conditional that checks if there even is a picture. So you can just do this:
if (/**Over here, you must check if the file exists and it is an image.**/) {
//Over here, you would want to turn the page's background into the image.
}
But, you need to have a function, or else the whole thing will only run at the very start of the page's load. You need to add an event listener or something that checks when the file is chosen. If you don't know how to do that, then you can just search it up. Or, you could find something on Stack Overflow that relates to it. Like this:
How to check if input file is empty in jQuery
Hope this helps! If you have any further questions, please tell me. I am new on Stack Overflow, so I need to know how I can improve. Thanks!
I'am changing the html code from javascript and want to call same function from created "div"s. but it is not called.
As you can see 'html' which is formed after function invoke also has class="screen" but created 'div's doesn't support it.
var i;
var clear = 2;
$("#container").click(function() {
var clickid = $(this).attr('id');
var left = document.getElementById(clickid).offsetLeft;
var top = document.getElementById(clickid).offsetTop;
var height = document.getElementById(clickid).offsetHeight;
var width = document.getElementById(clickid).offsetWidth;
var x = document.getElementById(clickid).value;
orient = prompt("vertical or horizontal ?");
numdiv = prompt("How many divisions should be created ?");
var divsper = [];
var html = "";
for (i = 0; i < numdiv; i++) {
per = prompt("Percentage of " + (i + 1) + "th division ?");
divsper.push(per);
}
if (orient == "vertical") {
for (i = 0; i < numdiv; i++) {
l = Math.floor(left + ((i * divsper[i] * width) / 100));
w = Math.floor((divsper[i] * width) / 100);
html = html + "<div id=" + clickid + " class=\"screen\" style=\"float:left; top:" + (top) + "px; left:" + (l) + "px; height:" + (height - clear) + "px; width:" + (w - clear) + "px; border:1px solid black;\"></div>"
}
document.getElementById(clickid).outerHTML = html;
//document.getElementById(clickid).unwrap();
}
});
* {
padding: 0px;
margin: 0px;
}
body {}
#container {
background-color: pink;
top=0%;
left=0%;
height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="screen">
</div>
Replace '$("#container").click(function() {' this line with '$("html").on('click', '[id*=container]', function() {'.
It will work for you.
var i;
var clear = 2;
$("html").on('click', '[id*=container]', function() {
var clickid = $(this).attr('id');
var left = this.offsetLeft;
var top = this.offsetTop;
var height = this.offsetHeight;
var width = this.offsetWidth;
var x = this.value;
orient = prompt("vertical or horizontal ?");
numdiv = prompt("How many divisions should be created ?");
var divsper = [];
var html = "";
for (i = 0; i < numdiv; i++) {
per = prompt("Percentage of " + (i + 1) + "th division ?");
divsper.push(per);
}
if (orient == "vertical") {
for (i = 0; i < numdiv; i++) {
l = Math.floor(left + ((i * divsper[i] * width) / 100));
w = Math.floor((divsper[i] * width) / 100);
html = html + "<div id=" + clickid + (i + 1) + " class=\"screen\" style=\"float:left; top:" + (top) + "px; left:" + (l) + "px; height:" + (height - clear) + "px; width:" + (w - clear) + "px; border:1px solid black;\"></div>"
}
this.outerHTML = html;
//this.unwrap();
}
});
* {
padding: 0px;
margin: 0px;
}
body {}
#container {
background-color: pink;
top=0%;
left=0%;
height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="screen">
</div>
Try using $('#container').on('click') instead. Dynamically generated html event handling is slightly different.
I have created a page where a list of members is shown. I created a Javascript function which shows the details of a user in a panel with id divpreview with position:absolute and z-index:100 the popup/panel does but I am not able to show it right above the the member.
<div runat="server" id="divpreview" class="preview">
</div>
<script type="text/javascript" language="javascript">
function showdiv(id, m, pos) {
var arr = new Array(7);
arr = id.split("###");
var divhtml = "";
divhtml += "<table border='1' style='background-color:#1C5E55;color:white;absolute' cellpadding='3' cellspacing='0'><tr><td>Sponsor Id</td><td>" + arr[0] + "</td></tr>";
divhtml += "<tr><td>Total Left Point</td><td>" + arr[1] + "</td></tr>";
divhtml += "<tr><td>Total Right Point</td><td>" + arr[2] + "</td></tr>";
divhtml += "<tr><td>Total Left Investment</td><td>" + arr[3] + "</td></tr>";
divhtml += "<tr><td>Total Right Investment</td><td>" + arr[4] + "</td></tr>";
divhtml += "<tr><td>Self Point </td><td>" + arr[5] + "</td></tr>";
divhtml += "<tr><td>Expiry Date</td><td>" + arr[6] + "</td></tr>";
divhtml += "</table>";
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").innerHTML = divhtml;
var left = m.clientX + 10;
if (pos == 1) {
left = m.clientX - 230;
}
else {
left = m.clientX + 10;
}
debugger;
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").style.left = left.toString() + 'px';
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").style.display = "block";
var top = 0;
top = document.documentElement.scrollTop + m.clientY - 50;
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").style.top = top.toString() + 'px';
}
function hidediv() {
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").style.display = "none";
}
function movediv(m, pos) {
var left = m.clientX + 05;
if (pos == 1) {
left = m.clientX - 200;
}
else {
left = m.clientX + 10;
}
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").style.left = left.toString() + 'px';
var top = 0;
top = document.documentElement.scrollTop + m.clientY - 50;
document.getElementById("ctl00_ContentPlaceHolder1_divpreview").style.top = top.toString() + 'px';
}
</script>
I want the panel to appear near the stars. What should I do.
Use
position: relative;
to the parent div. Position absolute element will "stop" when finding the closest positioned relative or positioned absolute element.
use this style on divpreview
<div runat="server" id="divpreview" class="preview" style="position:absolute;z-index:999;">
</div>
position: absolute;
parent div Position 'absolute'.
i write function which output top and left all div within div id=container
var main = $('#container'),
res = $('#result'),
bw = parseInt(main.css('border-left-width'), 10),
mT = main.offset().top + bw,
mL = main.offset().left + bw;
$('#btn1').on('click', function () {
var allCoords = $('div', main).map(function () {
return getCoords(this);
}).get().join('<br>');
res.html(allCoords); });
function getCoords(el) {
var $that = $(el),
pos = $that.offset(),
posTop = pos.top - mT,
posLeft = pos.left - mL;
var pos = el.id + ' top: ' + posTop + 'px; left: ' + posLeft + 'px;';
return pos;}
How can I get the value(left and top) in % relative div id container
please help me.Thank
Use math formula 100*yoursreensize/yourelementdivorsomething, like this:
var width = $(window).width();
var left = $('#me').position().left;
var percent = parseInt(100*left/width);
alert(percent);
#me{
position:relative;
left:20%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="me">Me</div>
I want to make a small game, but I have some start up problems.
When I try to get the position of track or trackCont, it always returns x: 0, y: 0. Doesn't get right position moving the DIV with:
float: right;
display: block;
and even doesn't work using:
position: absolute;
left: 100px;
Here's the code I am using:
var Player = new Array();
var trackEntity;
function getPosition(elem){
xPos = 0;
yPos = 0;
while(elem){
xPos += (elem.offsetLeft + elem.clientLeft);
yPos += (elem.offsetTop + elem.clientTop);
elem = elem.offsetParent;
}
return {x: xPos, y: yPos};
}
window.onload = function(){
trackEntity = document.getElementById("trackCont");
for (i = 0; i < 4; i += 1){
Player[i] = new Object();
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
Player[i].entity = document.getElementById("p" + i);
Player[i].entity.style.backgroundColor = "rgb("
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) +
")";
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20;
Player[i].entity.style.top = (getPosition(trackEntity).y) + 20;
}
}
http://jsfiddle.net/dh8uf6Lp/
You need to supply a unit to when assigning a value to css left.
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20 +"px";
If you assign a value to a css dimension or position property it will not update when no unit is given.
It seems that when getPosition(trackEntity) is called it doesn't know where it is in the DOM. This is caused by
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
This causes the browser to redraw all elements and trackEntity loses it reference.
Solution: do not insert html via innerHTML, but create the div and append it to the DOM.
Player[i].entity = document.createElement("div");
Player[i].entity.id = "p" + i;
//etc.
document.body.appendChild(Player[i].entity);
//Run position code.
http://jsfiddle.net/dh8uf6Lp/3/