Replace an existing element - javascript

if (yardss > 0.1 && yardss < 0.3) {
var img = document.createElement("img");
img.src = "images/wrench1.jpg";
img.align = "center";
document.body.appendChild(img);
} else if (yardss > 0.3) {
var img = document.createElement("img");
img.src = "images/wrench.jpg";
img.width = 500;
img.height = 300;
document.body.appendChild(img);
}
This script is activated by the user clicking on a button, and it prompts the user to enter a certain number of yards. If the yards are above a certain number, it displays a certain sized wrench. If it is below a certain number, it displays a different sized wrench.
My problem is that because the script can be run over and over again by clicking on the button, every time that the script is run, a new image of a wrench is produced below the previous image, creating a really long web page with a lot of images.
How do I make the newly created image replace the image created from the previous running of the script, instead of having the page fill with images from the script being run multiple times?

Use replaceChild instead of appendChild.

You can just change the .src property on the current image. There is no need to create a whole new image:
// get the current image object
// assumes you set id="wrenchImg" on it
var img = document.getElementById("wrenchImg");
if (yardss > 0.1 && yardss < 0.3) {
img.src = "images/wrench1.jpg";
img.height = ... // set this to whatever you need it to be for this image
img.width = ... // set this to whatever you need it to be for this image
img.align = "center";
} else if (yardss > 0.3) {
img.src = "images/wrench.jpg";
img.height = 300;
img.width = 500;
img.align = "left";
}
If you have any other properties of the image that must also be changed (height or width or alignment, for example), then you can add those to each branch of the if/else, but doing it this way, you have to fully initialize the image object because it may have been set a different way based on the previous image.

Don't create the img element again and again. Just create once and set some id on it. Then just change the src and width, height etc..
In HTML:
<img id= "wrench_img"/> // Setting id as wrench_img
In JavaScript:
function changer(yardss) {
var img1 = document.getElementById("wrench_img"); // Get the img
if (yardss > 0.1 && yardss < 0.3) {
img1.src = "images/wrench1.jpg"; // Change the src
img1.align = "center";
} else if (yardss > 0.3) {
img1.src = "images/wrench.jpg"; // Change the src
img1.width = 500; // Change width
img1.height = 300;
}
}
In your code, you were appending new image elements to the document.body. That is why you were getting multiple image elements. But if you look at this code, we don't create the image elements multiple times. We just change the one created.
Online Demo

Related

<img>(screen.width, screen.height) [duplicate]

I'm trying to change the size of an image with JavaScript. The jS file is separate from the HTML page.
I want to set the height and width of an image in the JS file. Any good ways on doing this?
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
If you want to resize an image after it is loaded, you can attach to the onload event of the <img> tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for <img>).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:
<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
onload="resizeImg(this, 200, 100);">
<script type="text/javascript">
function resizeImg(img, height, width) {
img.height = height;
img.width = width;
}
</script>
Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:
var i,L=document.images.length;
for(i=0;i<L;++i){
document.images[i].style.height = 'auto'; //setting CSS value
document.images[i].style.width = 'auto'; //setting CSS value
// document.images[i].height = ''; (don't need this, would be setting img.attribute)
// document.images[i].width = ''; (don't need this, would be setting img.attribute)
}
you can see the result here
In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.
html:
<div>
<img onmouseover="fifo()" onmouseleave="fifo()" src="your_image"
width="10%" id="f" >
</div>
js file:
var b=0;
function fifo() {
if(b==0){
document.getElementById("f").width = "300";
b=1;
}
else
{
document.getElementById("f").width = "100";
b=0;
}
}
Direct manipulation
HTML tag declaration for image:
<img id="my-img" src="src/to/your/image.jpg" width="1280px" height="720px" />
<!-- OR -->
<img id="my-img" src="src/to/your/image.jpg" style="width: 1280px; height: 720px;" />
Handling html tag by direct access to object image:
const myImg = document.getElementById("my-img");
// Set a new width and height
myImg.style.width = "800px";
myImg.style.height = "450px";
// Or set a new width and height by attribute
// This option is not advisable because the attribute has a
// low priority over the style property.
myImg.setAttribute("width", 800);
myImg.setAttribute("height", 450);
Functions for manipulation
Using the updateImageSizeWithWidth or updateImageSizeWithHeight method below, you can increase or decrease any image without having to explicitly specify the exact width and height, you only need one value out of these two to update the image size.
/**
* Update image size using width
*
* param {HTMLImageElement} img
* param {number} newWidth
*/function updateImageSizeWithWidth(img, newWidth) {
// Getting the width and height of the current image
const oldWidth = Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
// Getting proportional height with new width
const newHeight = (newWidth * oldHeight)/oldWidth;
// Setting dimensions in the image
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
/**
* Update image size using height
*
* param {HTMLImageElement} img
* param {number} newHeight
*/
function updateImageSizeWithHeight(img, newHeight) {
// Getting the width and height of the current image
const oldWidth = Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
// Getting proportional height with new width
const newWidth = (newHeight * oldWidth)/oldHeight;
// Setting dimensions in the image
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
updateImageSizeWithWidth(myImg, 800);
// Or
updateImageSizeWithHeight(myImg, 450);
// This one has print statement so you can see the result at every stage if you would like. They are not needed
function crop(image, width, height)
{
image.width = width;
image.height = height;
//print ("in function", image, image.getWidth(), image.getHeight());
return image;
}
var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());
You can do this:
.html file:
<img src="src/to/your/img.jpg" id="yourImgId"/>
.js file:
document.getElementById("yourImgId").style.height = "heightpx";
The same you can do with the width.

When iterating through HTML elements, some elements are returning an empty image when using domtoimage.toPng()

I am trying to iterate through all the widgets (Charts/tables etc) that is currently being contained within a div to be generated as a png by utilizing domtoimage.toPng() however, it is only able to return me the PNG result of the first widget and not the following widgets. The following widgets will only display a empty png.
Image returned as follows
After some debugging,
I think domtoimage.toPng() is only able to return me the appropriate image of the HTML element when the HTML div element has the attributes of gs-x = 0 and gs-y = 0 which renders it as the first div in the div stack
Question
What is actually going on? Why cant all the widgets as represented by their divs that I am iterating through be converted into an actual png that I can use?
Code
async function convertToPng(doc,page,doc_width,doc_height,doc_wh_ratio) {
// window.html2canvas = html2canvas;
// Go to next page
doc.addPage();
let chartNodes = page.childNodes;
var previousImgWidth = null;
var previousImgHeight = null;
for(let i =0; i < chartNodes.length; i++){
console.log(chartNodes[i]);
console.log(chartNodes[i].firstChild.firstChild);
if(chartNodes[i].firstChild.firstChild.tagName == 'TABLE'){
if(i > 0){
doc.addPage();
}
(doc.autoTable({ html: chartNodes[i].firstChild.firstChild }));
}
else{
console.log("CONVERT TO PNG CHECK RESULT FALSE XXXX");
let options = { "cacheBust":true }
let dataUrl = await domtoimage.toPng(chartNodes[i]);
console.log('~~~~~~~~~');
console.log(dataUrl);
console.log('~~~~~~~~~');
let img = new Image();
dataUrl = await loadImage(dataUrl);
img.src = dataUrl;
console.log(doc_width);
console.log(img.width);
console.log(img.height);
// doc.addImage(dataUrl, 'PNG', 2, 2, img.width, img.height); // Set height as limiting dimension
console.log(dataUrl);
console.log("imgOnLoad event entered");
doc.addImage(dataUrl, 'PNG', previousImgWidth + 2,2, 0, (img.height * (25.4 / 96) - 4)); // Set height as limiting dimension
previousImgWidth = (img.width * (25.4 / 96) - 4);
//Has to start a new line if width no longer has space
if(previousImgWidth +(img.height * (25.4 / 96) - 4) >doc_width ){
previousImgHeight = (img.height * (25.4 / 96) - 4) +2;
}
}
}
console.log("Convert to png function has ended");
}

How to detect if an image was clicked

I am trying to detect if an image was clicked. To give some context, I am making a cookie clicker game where if you click it 10 times, a new image will appear which will give double points. For the first image I used
document.querySelector('#clickme1').onclick=scooore;
Then I am adding new images with the following function:
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
My problem is how do I add to my variable (scree) since it is local and the first way needs to use a whole diff function.
function scooore() {
scree = scree + 1;
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times";
Been working for 40+ mins on this probably 1 line of code solution and couldn't find a solution so turning to the nice people at stack overflow
In addition to the code I posted below, what will really help you as you continue to develop your project is if you have an array of data for each image (whether that is an object or another array).
// Put on outside so that image may change instead of clone
var img = document.createElement("img")
// Fill out initial image specs
img.src = src
img.width = width
img.height = height
img.alt = alt
function show_image(src, width, height, alt) {
img.src = src
img.width = width
img.height = height
img.alt = alt
}
var scree = 0
function scooore() {
scree++
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times"
// If score is divisible by 10
if (scree % 10 === 0) {
show_image(src, width, height, alt)
}
}
document.querySelector('#clickme1').onclick = scrooore()

Explorer - canvas image editing issue

I'm currently building a site that comes with a set of icons. They are white .png images with a transparent area. Each image is placed over a div whose background colour changes on mouseover/mouseout events.
I wrote a small JavaScript function that I can use to set the white portion of each .png to whatever the header background colour is so that the images blend in with the header and all you see is the transparent cut-away area change on mouse events - it's quite a nice effect.
So the white portion (not the transparent part) of the image should be changed to whatever the header background colour is, and the function works really great on Firefox, but for some reason doesn't work so well on Explorer (11).
Is there something I'm not seeing here? Here's the code that does the image editing - all I need to do is pass the id of the image and the hexadecimal colour string:
function setImageBg(
imageID,
imageColor
) {
var img = document.getElementById(imageID);
var canvas = document.createElement('canvas');
// Get the red, green and blue values from the hex color
// string.
var redMix = parseInt(imageColor.substr(1, 2), 16);
var greenMix = parseInt(imageColor.substr(2, 2), 16);
var blueMix = parseInt(imageColor.substr(5, 2), 16);
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
// Get the image data...
var pixelData = canvas.getContext('2d').getImageData(0, 0, img.width, img.height);
var imgData = pixelData.data;
var ctx = canvas.getContext('2d');
var imgDataURL;
// Edit the image data.
for (imagePos = 0; imagePos < ((img.width * img.height) * 4); imagePos += 4) {
if (pixelData.data[(imagePos + 3)] <= 99)
continue;
imgData[imagePos] = redMix;
imgData[(imagePos + 1)] = greenMix;
imgData[(imagePos + 2)] = blueMix;
}
ctx.putImageData(pixelData, 0, 0);
imgDataURL = canvas.toDataURL();
document.getElementById(imageID).src = imgDataURL;
}
Like I say, it's great on Firefox - on Explorer all I see is the div, which still dutifully changes colour on mouse events. It's as though the entire image has been made transparent.
Any help would be greatly appreciate, much obliged.
UPDATE:
Ok, so I thought I'd cracked this...here's what happened.
The problem was that the image was loading and being edited in both IE and FF, when I noticed the image had loaded and rendered in IE I thought I'd found and fixed the bug...but after a refresh the image again disappeared.
I scratched my head over it for a bit then decided I'd wasted enough time on it and brushed it aside. Now everything else is in place and working, so I'm back to this and it's a proper head scratcher.
So - IE DOES actually load and edit/render the image, when you initially open the page that is. If you refresh the page, the image disappears...or does it?
I made some adjustments to the code, using alert()'s to try and diagnose the problem, I decided what I do was add some code to check the source file - instead of diving in and changing the pixel colours - I decided to check the image before it is being edited.
Seems that, on the second run of my function - the image loaded is completely black and completely transparent. All pixels have a value of 0!
What does this mean? There's definitely something there, but not what should be.
Is htis a cacheing issue? I messed about with it for a bit, it's odd that IE will load and display the image initially but will neglect to do so after a refresh, but Ff is fine. I tried a few tricks to disable cacheing but nothing works...so now I'm thinking, perhaps it's something else.
Any ideas would be greatly appreciated, I mean it's not a deal-breaker. Everything is fine without this single feature but it's a shame if I can't get it to work.
For anyone interested, here's the updated function after various changes/edits:
function setImageBg(
imageSource,
imageSrc,
imageDst,
imageColor
) {
var img = document.getElementById(imageSrc);
var canvas = document.createElement('canvas');
var redMix = parseInt(imageColor.substr(1, 2), 16);
var greenMix = parseInt(imageColor.substr(3, 2), 16);
var blueMix = parseInt(imageColor.substr(5, 2), 16);
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(0, 0, img.width, img.height);
var imgData = pixelData.data;
var ctx = canvas.getContext('2d');
var imgDataURL;
// Here's a change I made - on the first call of this function
// when the page loads, all is good - on the second call after a
// refresh this always returns on IE - it's as though the loaded
// image (from file) is completely black and transparent
// (everything is 0)...problem is the image file is never actually
// altered - the loaded image is altered but the actual file never
// changed - very odd...
//
if (pixelData.data[0] == redMix) {
if (pixelData.data[1] == greenMix) {
if (pixelData.data[2] == blueMix) {
document.getElementById(imageDst).src = document.getElementById(imageSrc).src;
return;
}
}
}
for (imagePos = 0; imagePos < ((img.width * img.height) * 4); imagePos += 4) {
if (pixelData.data[(imagePos + 3)] <= 99)
continue;
pixelData.data[imagePos] = redMix;
pixelData.data[(imagePos + 1)] = greenMix;
pixelData.data[(imagePos + 2)] = blueMix;
}
ctx.putImageData(pixelData, 0, 0);
document.getElementById(imageDst).src = canvas.toDataURL();
return true;
}

Adding an image onto another image Javascript (for a close button)

I am looking for a simple way to add a close icon image to another image in Javascript. I am trying to position an icon in the top right corner of the an image.
Code So Far:
function drawImages(imagevalue){
var array = localStorage.getItem('images');
array = JSON.parse(imagevalue);
//Add HTML to screen:
//Clear the elements that might already be in the div so they don't appear twice:
var theDiv = document.getElementById("saveArea");
while (theDiv.firstChild) {
theDiv.removeChild(theDiv.firstChild);
}
for (var x=0; x < array.length; x++){
//Create image for each value in array:
var img = document.createElement("img");
img.src = array[x];
img.width = 300;
img.height = 150;
img.style.marginRight="10px";
img.className = "saveImg";
//this image needs to be placed in the top right corner of the
//image named img.
var close = document.createElement("close");
close.src="close.png";
document.getElementById("saveArea").appendChild(img);
}
}
CSS doesn't work? Something like position:relative;right:0;top:0;

Categories