javaScript: window.open not displaying background image - javascript

Please help me, I have been working on this for hours. I have just started playing with JavaScript.
So I have a button that loads a new browser window, loads background image. As below, no problems.
HTML
<script>
setBackground();
</script>
JavaScript
function setBackground() {
document.body.style.backgroundColor = "#000000";
document.body.style.backgroundImage = "url(bg.jpg)"
}
Then I try to load another window on button click but the background image will not work. The window works, I can change the background color no problem, but I can't get the image to load. code below.
//load screen on button click
document.getElementById("startButton").onclick = function() {
load()
};
function load() {
//create the new screen
newWindow = window.open("", "", "width=1550, height=800");
newWindow.id = "game";
newWindow.document.body.style.backgroundColor = "#000000";
newWindow.document.body.style.backgroundImage = "url(bg.jpg)";
}
The files and images are located in the same folder, I'm using the same image, it works in the first example but not the second.
Please help!!! Thanks in advance.

Check this link and click on Run
https://www.w3schools.com/code/tryit.asp?filename=GM9IO9Q6SDNL
try this.
<!DOCTYPE html>
<html>
<body onload="setBackground()" >
</body>
<script>
function setBackground() {
document.body.style.backgroundImage = "url(https://www.w3schools.com/html/pic_trulli.jpg)"
newWindowSetBackgroundload()
}
function newWindowSetBackgroundload() {
//create the new screen
var newWindow = window.open("", "", "width=1550, height=800");
//Id use for Uniq thats why its render only one time
// newWindow.id = "game";
//use class for multiple windows genration
newWindow.class = "game";
newWindow.document.body.style.backgroundColor = "#000000";
newWindow.document.body.style.backgroundImage = "url(https://www.w3schools.com/html/pic_trulli.jpg)";
}
</script>
</html>

Related

Getting the width and height of a div or image after it finished loading

I'm creating an image gallery and I need to know the size of the div containing the image or the image itself after it loads. How can I get that? I've tried everything but it gives me the size of the DIV before it loads, which is 1px X 1px.
Basically everything is hidden, you click a link and the image displays, so the div goes from 1px by 1px to for example, say 419px by 1000px. How do I get that final size after the DIV or Image loads? the size can change depending on the device used and the image loaded. Is there anyway to get this information using just JavaScript?
Here's the function. If possible I would like to get the height of the image or the DIV after the image loads in the same function.
here's the function that i am testing
function ShowArt(nam,imgs,)
{
var currentPosition = parseInt(movingDivObj.style.top);
var scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
movingDivObj.style.top = currentPosition + scrollPos + "px";
movingDivObj.style.display = "block";
document.getElementById("close").style.display = "block";
document.getElementById("selectedart").style.display = "block";
document.getElementById("artname").style.display = "block";
document.getElementById("background").style.display = "block";
display.src = imgs;
document.getElementById("artname").textContent= nam;
scrollPosition = window.pageYOffset;
document.body.style.position = "fixed";
document.body.style.top = `-${scrollPosition}px`;
}
Thanks!
Try using this DOM event listener, in the callback function you can write the necessary code to get your value I presume:here
In the same way that the "load" event works for the body, it works for images. So you could attach an "load" event on the image and when it triggers, measure the width/height.
const img = document.querySelector('#img')
img.addEventListener('load', (event) => {
console.log('width', event.target.width)
console.log('height', event.target.height)
})
img.src = 'https://via.placeholder.com/900x1000'
Have you tried:
<script>
var myImg = document.getElementById('image');
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
console.log(realWidth);
</script>
Solution 1:
Use this Solution in your JS file
JavaScript:
window.onload = () => {};//enter the code that gets the image or divs width and height in the {} brackets`
The window.onload function waits till the DOM is loaded and then executes a function. It is used mostly when you need to get default values from a predefined and static element.
Further Readings: https://www.w3schools.com/jsref/event_onload.asp
Solution 2:
NOTE: Use this only if you are using a 'script' tag to use the JS code in your HTML.
Use the script tag at the end of your HTML document
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--Your code goes here-->
<script src="myScript.js"></script>
</body>
</html>
Thanks guys I appreciate all the help. I finally found an answer that worked though I got some great ideas. The answer was to have the images preload and when I did that it gave me the height of the image I needed for the next steps. Again thanks very much! I appreciate it. The code I used for this is below. After the images are preloaded I am able to get the width / height of the images so they work in the gallery as planned. It worked like a charm.
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"Photos/AloneInTheStorm.jpg",
"Photos/deepinthought.jpg",
"Photos/68degrees.jpg",
"Photos/forgotten.jpg",
"Photos/babylycan2.jpg",
"Photos/americancoot.jpg"
)

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

how to save a picture taken with window.getusermedia in js

Currently i am working on a open webapp camera, right now i have implemented the camera setup(live stream as viewport, take picture button, capture, display taken picture in corner... etc) but now i am running into the issue of how to save that picture for the user to their device or computer, this app is currently being designed for mobile b2g primarily. I know most people are gonna tell me security issues!!! i dont mean tell the device exactly where to put it. I mean something like
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('embedImage');
var button = document.getElementById('saveImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'+
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'+
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<body>
<img id="embedImage" alt="Red dot"/>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</body>
</html>
that specific code executed on mobile triggers the file to automatically be saved on click of the button. now what i want to do is use that to take my picture from its var its in and save it as that file, for example that will be in downloads folder.
this is what my code is currently https://github.com/1Jamie/1Jamie.github.io
any help would be appreciated and this is the current running implementation if you want to take a working look http://1Jamie.github.io
This worked for me when I was playing around with getUserMedia - I did notice that you did not have the name of the method in the proper case and it is a method of the navigator.mediaDevices interface - not a method of the window directly...
References:
[Navigator for mozilla]https://developer.mozilla.org/en-US/docs/Mozilla/B2G_OS/API/Navigator
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices
[mediaDevices for chrome and android]https://developers.google.com/web/updates/2015/10/media-devices?hl=en
var video = document.getElementById('monitor');
var canvas1 = document.getElementById('photo1');
var img1 = document.getElementById('canvasImg');
navigator.mediaDevices.getUserMedia({
video: true
}).then(function (stream) {
video.srcObject = stream;
video.onloadedmetadata = function () {
canvas1.width = video.videoWidth;
canvas1.height = video.videoHeight;
document.getElementById('splash').hidden = true;
document.getElementById('app').hidden = false;
};
}).catch(function (reason) {
document.getElementById('errorMessage').textContent = 'No camera available.';
});
function snapshot1() {
canvas1.getContext('2d').drawImage(video, 0, 0);
}
"save_snap" is the id of a button - Disclaimer I am using jQuery- but you should easily see where this corresponds to your code:
$("#save_snap").click(function (event){
// save canvas image as data url (png format by default)
var dataURL = canvas2.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
$('#canvasImg').attr("src" , dataURL);
$('#downloader').attr("download" , "download.png");
$('#downloader').attr("href" , dataURL);
//* trying to force download - jQuery trigger does not apply
//Use CustomEvent Vanilla js: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
// In particular
var event1 = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
//NOW we are effectively clicking the element with the href attribute:
//Could use jQuery selector but then we would have to unwrap it
// to expose it to the native js function...
document.getElementById('downloader').dispatchEvent(event1);
});

JavaScript - Clicking on an image

I am programming a browser game in JavaScript and need to create a Card Class.
This class has (with other variables) an image, which should be displayed when I create an object. How do I display the object's image and call a function when the image is clicked?
With this code I can display the image wherever I want, but the OnClick function is called instantly when I open the .htm file instead of when I click in the image.
<html>
<head> </head>
<body>
<script type="text/javascript">
function Card(photo){ // this is my object
this.randomVariable=42;
this.pic = new Image(); // creating an Image object inside my Card class.
this.pic.src=photo;
this.pic.height = 300;
this.pic.width = 200;
this.pic.style.position="absolute"; // this 3 lines should set the image's position, and it does.
this.pic.style.top = 50 + "px";
this.pic.style.left = 50 + "px";
this.OnClick = document.write("lala");
}
var myObject = new Card("cardback.jpg");
myObject = document.body.appendChild(coso1.pic); // is this how I should create the image? It appears where I want, but it doesn't seem a "clean" programming.
myObject.OnClick = document.write("lala" + coso1.pic.offsetLeft + coso1.pic.offsetTop); // this is casted when I open the file, and not when I click on the image. *sadface*
</script>
</body>
</html>
Please, some help with detecting when I click on the image and displaying the image in a less dirty way (if it's possible)?
Thanks in advance!
http://jsfiddle.net/CTWWk/1/
var image = new Image();
image.src = 'https://www.google.co.il/images/srpr/logo4w.png';
image.onclick = function(){
alert('I Clicked an image now !');
};
var divy = document.getElementById('divy');
divy.appendChild(image);
Made some changes to your code. Hope it helps!
<html>
<head> </head>
<body>
<script type="text/javascript">
function Card(photo){
var cardInstance = new Image();
cardInstance.src = photo;
cardInstance.addEventListener('click', function (e) {
alert(1);
});
return cardInstance;
}
var myObject = new Card("cardback.jpg");
document.body.appendChild(myObject);
</script>
</body>
</html>

Change pre-defined body background image

I found this script to change the body's background image when you click a link. It works, great except the only problem is is that I cannot have a pre-defined bg image in the css or else it won't change.
So I remove the css for the background image and it switches the images fine, but I want an image to be default to start with.
Script:
<script language="JavaScript">
<!--
var backImage = new Array(); // don't change this
backImage[0] = "images/bg0.png";
backImage[1] = "images/bg1.png";
backImage[2] = "images/bg2.png";
backImage[3] = "images/bg3.png";
backImage[4] = "images/bg4.png";
backImage[5] = "images/bg5.png";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
}
}
//-->
</script>
Link:
Change2
And, for example, I want bg0.png to be the background by default when the page loads.
It would also be great if it was possible to fade between the bg images.
Thanks in advance.
Keep the background in the CSS, and use this code instead
var backImage = [
"images/bg0.png",
"images/bg1.png",
"images/bg2.png",
"images/bg3.png",
"images/bg4.png",
"images/bg5.png"
];
function changeBGImage(whichImage) {
if (document.body){
document.body.style.backgroundImage = 'url('+backImage[whichImage]+')';
}
}
To change the background if you have one defined in the css you need to alter: document.body.style.backgroundImage attribute

Categories

Resources