javascript - create image element and randomly place within div in html5 - javascript

In my html document I have a div with id="containerRight". In the same directory where the html document is I have an image that needs to be added to the html. Using javascript I want to add 5x the same image into the div and scatter them randomly within the div. I'm struggling with adding 5x the same image from the hdd and positioning them randomly within the div. I have tried this so far:
<!DOCTYPE html>
<html>
<head>
<script>
function insert_picture(){
var newPicture = document.createElement("img");
var destinationParent = document.getElementByID("containerRight");
destinationParent.appendChild(newPicture);
}
function ImgRandomPosition()
{
var left = generateRandom();
var top = generateRandom();
var image = insert_picture();
var imagestyle = document.getElementById("imgRight").style;
imagestyle.position = "absolute";
imagestyle.top = top;
imagestyle.left = left;
}
</script>
</head>
<body onclick="insert_picture()">
<div id="containerRight">
<img id="imgRight" src="smiley.png" alt="" />
</div>
</body>
</html>

I have changed the code to the following and it adds images to the div containerRight next to each other:
function insert()
{
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
}
Then the next issue is to position images randomly within the same div id="containerRight".
The code below does add images randomly to the body of the html not the div.
Any further thoughts greatly appreciated:
function insert()
{
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
ImgRandomPosition(imgAdded);
}
function ImgRandomPosition(imgAdded)
{
var left = Math.floor((Math.random() * 400) + 1)+"px";
var top = Math.floor((Math.random() * 400) + 1)+"px";
var imagestyle = imgAdded.style;
imagestyle.position = "absolute";
imagestyle.top = top;
imagestyle.left = left;
}

change your code to
function insert_picture()
{
var newPicture = document.createElement("img");
var destinationParent = document.getElementByID("containerRight");
destinationParent.appendChild(newPicture);
newPicture.src = "smiley.png";
ImgRandomPosition(newPicture);
}
function ImgRandomPosition(imgObj)
{
var left = generateRandom();
var top = generateRandom();
var imagestyle = imgObj.style;
imagestyle.position = "absolute";
imagestyle.top = top;
imagestyle.left = left;
}
Now when you click on the body <body onclick="insert_picture()"> this method will add an image somewhere on the body

Related

HTML CANVAS - Preload Issue or OnLoad issue - Why do I have to click twice?

I have an HTML page with 2 canvases side-by-side. The left one has a clickable upper region. The right one is where all the drawing takes place. I want the user to click the region on the left, which will load a new image on the right, and replace the one that is already there, but I have to click twice for the new image to show up. Why is this? See code.
THE HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#centerAll {
margin-left:auto;
margin-right:auto;
width:1300px;
}
</style>
</head>
<body>
<div id="centerAll">
<canvas id="TheLeftCanvas" width="300" height="500"
style="border:2px solid #999999;"></canvas>
<canvas id="TheRightCanvas" width="900" height="500"
style="border:2px solid #999999;"></canvas>
<script type="text/javascript" src="whyClickTwiceForImage.js">
</script>
</div>
</body>
</html>
AND THE JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var rightCanvas = document.getElementById("TheRightCanvas");
//THE EMPTY CANVAS ON THE RIGHT, WHICH DRAWS THINGS
var rightCtx = rightCanvas.getContext("2d");
var leftCanvas = document.getElementById("TheLeftCanvas");
//THE EMPTY CANVAS ON THE LEFT, WHICH HANDLES USER CLICKS
var leftCtx = leftCanvas.getContext("2d");
var currentMouseXcoor = 0;
var currentMouseYcoor = 0;
var imagesToLoad = 0; //USED TO PRE-LOAD SOME OTHER VISUALS, BEFORE THE USER STARTS
var imagesLoaded = 0;
var picturesTheUserCanChoose = ["pic01.png", "pic02.png",
"pic03.png", "pic04.png", "pic05.png"];
var nameOfPicTheUserChose = "pic05.png"; //LET'S JUST SAY "pic05.png" IS A PLACEHOLDER PICTURE... TO START OFF
var legitMouseClick = 0; //DID THE USER CLICK IN THE UPPER REGION OF THE LEFT CANVAS?
var loaded = function(){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER VISUALS BEFORE THE USER STARTS
imagesLoaded += 1;
if(imagesLoaded === imagesToLoad){
imagesToLoad = 0;
imagesLoaded = 0;
drawScreen(); // OK... ALL LOADED.... SO DRAW THE SCREEN
}
}
var loadImage = function(url){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER PICS BEFORE THE USER STARTS
var image = new Image();
image.addEventListener("load",loaded);
imagesToLoad += 1; // ADD THE NUMBER TO THE IMAGES NEEDED TO BE LOADED
image.src = url;
return image; // ...AND RETURN THE IMAGE
}
//--------------------------------------------------------------
leftCanvas.addEventListener('mouseup', function(evt) { var
mousePos = doMouseUp(leftCanvas, evt);
currentMouseXcoor = mousePos.x; currentMouseYcoor =
mousePos.y; processMousePosition();}, false);
//--------------------------------------------------------------
function drawScreen(){
clearScreen();
rightCtx.drawImage(picture1,0,0,100,100);
}
//THIS FUNCTION PRESUMABLY LOADS IMAGES ON-THE-FLY... BUT WHY DOES THE LEFT CANVAS REGION HAVE TO BE CLICKED TWICE FOR THE NEW IMAGE TO SHOW?
function processMousePosition() {
if(currentMouseYcoor >= 0 && currentMouseYcoor <= 50){
//IF THE CLICK IS IN THE UPPER REGION OF THE LEFT CANVAS
nameOfPicTheUserChose = picturesTheUserCanChoose[0];
//WE'LL SAY THE USER CHOSE THE VERY FIRST PIC IN THE ARRAY
picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose);
picture1.onload = legitMouseClick = 1;//I JUST MADE UP FOR SOMETHING TO HAPPEN WHEN THE NEW PICTURE LOADS???
alert(nameOfPicTheUserChose); // THE ALERT CORRECTLY SHOWS THE NAME OF THE FIRST PIC IN THE ARRAY
}
drawScreen();
}
function doMouseUp(leftCanvas, evt){
var rect = leftCanvas.getBoundingClientRect();
return { x: evt.clientX - rect.left, y: evt.clientY - rect.top};
}
function clearScreen(){
rightCtx.clearRect(0, 0, 900, 500);
leftCtx.clearRect(0, 0, 300, 500);
}
//var someOtherVisual1 =
//loadImage("backgroundArtFolder/someOtherVisual1.jpg");
//var someOtherVisual2 =
//loadImage("backgroundArtFolder/someOtherVisual2.png");
//var someOtherVisual3 =
//loadImage("backgroundArtFolder/someOtherVisual3.png");
//var someOtherVisual4 =
//loadImage("backgroundArtFolder/someOtherVisual4.png");
//var someOtherVisual5 =
//loadImage("backgroundArtFolder/someOtherVisual5.png");
var picture1 = loadImage("picturesFolder/pic05.png");
//LET'S JUST PRELOAD "pic05.png" AS A PLACEHOLDER... TO START OFF
}
You can change the image load on click in js file picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose); to picture1 = loadImage("picturesFolder/"+nameOfPicTheUserChose); and picture1.onload = legitMouseClick = 1; to 'legitMouseClick = 1'

JS style.marginLeft & marginRight = 'auto' not working

Using the Yahoo Weather API.
When trying to set the style margins via JS, nothing happens.
Here is my script:
<script>
var cBackFunction = function (data) {
console.log(data);
var location = data.query.results.channel.location;
var condition = data.query.results.channel.item.condition;
var wind = data.query.results.channel.wind;
var units = data.query.results.channel.units;
var link = data.query.results.channel.link;
var lastUpdated = data.query.results.channel.lastBuildDate;
var conditionCode = condition.code;
var conditionText = condition.text;
var img = document.createElement("IMG");
img.src = "https://s.yimg.com/zz/combo?a/i/us/we/52/" + conditionCode + ".gif";
img.style.marginLeft = "140px";
document.getElementById('Weather-Description2').appendChild(img);
document.getElementById('Weather-Location2').innerHTML = location.city;
document.getElementById('Weather-Region2').innerHTML = location.region;
document.getElementById('Weather-Temp2').innerHTML = condition.temp;
document.getElementById('Weather-Unit2').innerHTML = units.temperature;
document.getElementById('Weather-WindSpeed2').innerHTML = wind.speed;
document.getElementById('Weather-Link2').href = link;
document.getElementById('lastUpdate2').innerHTML = lastUpdated;
document.getElementById('Weather-text2').innerHTML = "["+conditionText+"]";
document.getElementById('Weather-text2').style.marginLeft = 'auto'; //not working
document.getElementById('Weather-text2').style.marginRight = 'auto'; // not working
}
HTML:
<strong id="Weather-text2"></strong>
If I change the auto to a specific pixel like "100px" then it works.. can auto be used in JS for margins? The reason for auto on both marginLeft and marginRight is to auto-center the element. If so, how do I implement that correctly?
A <strong> element is, by default, display: inline.
Auto margins centre elements which are display: block (although since you would have width: auto as the default, this would have no practical effect unless you also reduced the width).
Set text-align: center on the nearest block ancestor element to centre the text.

Position JS search box over and image and make transparent

I would like to add a search box and make it transparent to a 80% degree and sit on the left or right of this image with padding http://www.holidays2crete.com/wp-content/uploads/2016/05/holiday-search-background.jpg.
I have tried following some of the examples on stackoverflow but managed to get nowhere.
<script src="http://scripts.distributenetwork.net/searchbox/searchbox_script_v3.js" type="text/javascript"></script>
<div style="width:405px;height:235px;" id="dt_searchcontainer_top"></div>
<script type="text/javascript">
var text = '#000000';
var background = '#FFFFFF';
var border = '#ffffff';
var container_id = 'dt_searchcontainer_top';
var whitelabel_url = 'quickstart.travelresults.net';
var departureairport = 'LON';
var destination = '';
var destination_data = '';
var boardbasis = 'AI~FB~HB~BB~SC~RO~OtherBoardBasis';
var starrating = '5~4~3~2~Other';
var new_window = true;
var customVariableName = ['QSUserGUID','awin_id','affilinet_id','td_id','afuture_id','gan_id'];
var customVariableValue = ['eded668a-58f7-468d-a542-0efa301810d9','107649','464082','1686829','102616','610263'];
var searchbox_title = '';
var brandlist = 'AIR~ESS~TCH~TCF~MAN~LCH~OTB~BSK~EBK~LMN~NLS';
load_searchbox('type3', whitelabel_url, text, background, border, container_id, departureairport, destination, destination_data, boardbasis, starrating, new_window, customVariableName, customVariableValue, searchbox_title, brandlist);
</script>
I also need to add it all into a wordpress page or to my front page.
Would anyone be kind enough to help me please :)

Get the images dimension from html

I have two images in two different section and div.I want to get the original dimension at same time and send to my java script file to do some calculation. How do I get the images dimension at the same time.
html file
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event);"/>
</section>
js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
In this code I am able to get the images dimension of images,But they return dimension of only one images.I want to get the dimension of both images at same time.
Something like this:
function OnImageLoad(evt) {
var img1 = evt.currentTarget;
var img2 = evt.currentTarget;
// what's the size of this image
var w1 = $(img1).width();
var h1 = $(img1).height();
var w2 = $(img2).width();
var h2 = $(img2).height();
You can not do that, they are async tasks. You can only calculate the size of the image only when they are completely loaded, so If first image is of higher size then the second image, it will take more time to calculate the first image size then the second.
What you can do is, fetch both the image sizes aynchronously, and when both of them are done you can do the calculations.
var sizes = [];
var counter = 0;
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
counter++;
sizes.push({
height: h,
width: w
});
if (counter == 2) {
callAnotherFunction(sizes)
}
}
prepending the variables with a custom value should make it possible.
HTML
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event,1);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event,2);"/>
</section>
JS
function OnImageLoad(evt, pre) {
var img = evt.currentTarget;
// what's the size of this image
eval("var w" + pre + " = $(img).width()");
eval("var h" + pre + " = $(img).height()");
Ive not tested this though.
function OnImageLoad() {
var img1 = document.getElementById("Image1");
var img2 = document.getElementById("Image2");
// what's the size of this image
var w1 = img1.width;
var h1 = img1.height;
var w2 = img2.width;
var h2 = img2.height;
}
Html:
<section id ="hi">
<img id="Image1" src = "images/hi.png"/>
</section>
<section id = "bye">
<img id="Image2" src = "images/hi.png"/>
</section>
Call this function on window.onload=OnImageLoad();
function OnImageLoad(evt) {
//This function will be called on each image load and will iterate all the image inside this dom
var images = $('img');
for(var i =0 ;i<images.length; i++) {
// what's the size of this image
var w = $(images[i]).width();
var h = $(images[i]).height();
//For each file you will have width and height of the image
console.log('width of image-'+i+': ',w);
console.log('height of image-'+i+': ',h);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<section id ="hi">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-green-orbs-icons-business/103491-3d-glossy-green-orb-icon-business-tool-screwdriver.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-orange-orbs-icons-business/105429-3d-glossy-orange-orb-icon-business-tool-hammer4-sc44.png" onload = "OnImageLoad(event);"/>
</section>
</body>
</html>
enter link description here

Simple javascript html image game

I have a simple game where image moves randomly and score increases when user clicks on it.
The first image displays before game is started, which when clicked calls the play() function in javascript, which hides that image and displays the image that is to be used for the game.
That is where my code is stuck, it does not call the function play(). I am new to javascript and html. Any help would be great!
Here is my code
<html>
<head>
<title>Image click Game!</title>
<script>
global var score = 0;
global var left=400;
global var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style = 'display : none';
game.style='display : block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX = Math.floor(Math.random()*11)-5;
var randomNumberY = Math.floor(Math.random()*11)-5;
left = left + randomNumberX;
top = top+randomNumberY;
var im = document.getElementById('image');
im.style.left = left;
im.style.top = top;
}
</script>
</head>
<body>
<div id ="firstDiv" style="display : block">
<img src="pics/playgame.gif" width="108" height="106" onClick = "play()"/></a>
</div>
<div id="game" style="display : none">
<p>"Score: " + score</p>
<img id="image" src="pics/gameImage.gif" onClick = "score++" style="position:absolute; left: 400; top: 100;"/></a>
</div>
</body>
</html>
There are a handful of things wrong with your code:
1) Your <img> tags are ended with a stray, unneeded </a> tag.
2) In your <img> tag, you should change to onClick = "play();"
3) I don't believe javascript supports the global keyword in that way.
4) To change CSS style, try this:
firstDiv.style.display = 'none';
game.style.display = 'block';
5) You cannot display javascript variables in this fashion: <p>"Score: " + score</p>...not to mention there is no declared variable 'score' to begin with!
Keep working at it, you only get better with practice.
Tyr this
<script>
var score = 0;
var left=400;
var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style.display='none';
game.style.display='block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX=Math.floor(Math.random()*11)-5;
var randomNumberY=Math.floor(Math.random()*11)-5;
left= left+randomNumberX;
top = top+randomNumberY;
var im= document.getElementById('image');
im.style.left=left;
im.style.top=top;
}

Categories