How can I exclude elements from the function effect - javascript

In this page when the user click "Show Image" button, a random image appear. that's good. I need the script only affect this image.
The problem is the header image disappear too, and I need to keep all other images displayed.
I need a solution
Code here:
https://codepen.io/Haitham1000/pen/aXjYzz
function display_random_image()
{
var theImages = [{
src: "http://farm4.staticflickr.com/3691/11268502654_f28f05966c_m.jpg",
width: "240",
height: "160"
}, {
src: "http://farm1.staticflickr.com/33/45336904_1aef569b30_n.jpg",
width: "320",
height: "195"
}, {
src: "http://farm6.staticflickr.com/5211/5384592886_80a512e2c9.jpg",
width: "500",
height: "343"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
// create random image number
function getRandomInt(min,max)
{
// return Math.floor(Math.random() * (max - min + 1)) + min;
imn = Math.floor(Math.random() * (max - min + 1)) + min;
return preBuffer[imn];
}
// 0 is first image, preBuffer.length - 1) is last image
var newImage = getRandomInt(0, preBuffer.length - 1);
// remove the previous images
var images = document.getElementsByTagName('img');
var l = images.length;
for (var p = 0; p < l; p++) {
images[0].parentNode.removeChild(images[0]);
}
// display the image
var targetContainer = document.getElementsByClassName("container");
targetContainer[0].appendChild(newImage);
}

If container is the only place where there will be images you want to remove (for example, the previous image), you can iterate over just the images it contains, rather than all images in the document. For example:
// remove the previous images
var targetContainer = document.getElementsByClassName("container")[0];
var images = targetContainer.getElementsByTagName('img');
var l = images.length;
for (var p = 0; p < l; p++) {
images[0].parentNode.removeChild(images[0]);
}
// display the image
targetContainer.appendChild(newImage);
Note that var targetContainer was moved to the top, that the [0] was added to it, and that images is now coming from targetContainer.getElementsByTagName.
Codepen

You are finding and then looping over every image on the page to remove it. Instead of var images = document.getElementsByTagName('img'); try getting images in the container and then replace them.
function display_random_image() {
....
var newImage = getRandomInt(0, preBuffer.length - 1);
//GET THE CONTAINER FIRST
var targetContainer = document.getElementsByClassName("container")[0];
//FIND THE IMAGES IN CONTAINER ONLY
var images = targetContainer.getElementsByTagName('img');
var l = images.length;
for (var p = 0; p < l; p++) {
images[0].remove();
}
// display the image
targetContainer.appendChild(newImage);
}

Related

html2canvas + jsPDF: concatenating pictures to form pdf shuffles up the pages

I am trying to download a dashboard created with plotly dashand having no built-in feature to do so, I have made a script that gets called on press of the download button.
This script is designed get all pages (from their class name), then it includes the textarea content and then, it takes a picture of each page, and aggregate them into a pdf.
function(n_clicks){
if(n_clicks > 0){
var pages = document.getElementsByClassName("page");
var pageArray = [];
for (var i = 0; i < pages.length; i++) {
var textareas = pages[i].getElementsByTagName("textarea");
for (var j = 0; j < textareas.length; j++) {
var div = document.createElement("div");
div.innerHTML = textareas[j].value.replace(/\\n/g, "<br />");
div.setAttribute("style", "font-size: 19px; margin-top: 15px;margin-right:50px;margin-left:50px");
textareas[j].parentNode.replaceChild(div, textareas[j]);
pageArray.push(pages[i]);
}
}
var pdf = new jsPDF('p', 'pt', 'letter');
var promises = [];
for (var i = 0; i < pageArray.length; i++) {
promises.push((function(index) {
return html2canvas(pageArray[index], {useCORS: true}).then(function (canvas) {
var imgData = canvas.toDataURL("image/png");
var scaledWidth = canvas.width * 0.75;
var scaledHeight = canvas.height * 0.65;
var x = (pdf.internal.pageSize.width - scaledWidth) / 2;
var y = (pdf.internal.pageSize.height - scaledHeight) / 2;
pdf.addImage(imgData, 'PNG', x, y, scaledWidth, scaledHeight);
if (index < pageArray.length - 1) {
pdf.addPage();
}
});
})(i));
}
Promise.all(promises).then(function() {
pdf.save("concatenated.pdf");
});
}
}
this works but the pages are getting shuffled up on download, it seems that it is randomly. I am not so good with js and I can't what is messing up. Hopefully someone can see where I am messing up

Why can't I change the zIndex here?

I have a bunch of divs positioned on top of an image.
I am trying to make the fraction hidden by the div to appear on the mouse hover. To achieve this I tried setting the zIndex of the div to be lower than the one of the image so it gets revealed. But I can seem to select ALL the divs.
Here is my javascript code:
window.onload = function () {
var block = document.getElementById('container');
block.addEventListener('mouseover', function () {
var blocks = document.querySelectorAll("#container div");
var index = 0, length = blocks.length;
for (var index = 0; index < length; index++) {
blocks[index].style.zIndex = 2;
}
});
for (var i = 0; i < 40; i++) {
for (var j = 0; j < 40; j++) {
var div = document.createElement("div");
div.className = "block";
div.style.left = j * 25 + 'px';
div.style.top = i * 25 + 'px';
div.style.display = "inline-block";
div.style.verticalAlign = "top";
div.style.zIndex = "1";
document.getElementById("container").appendChild(div);
}
var jump = document.createElement("br");
document.getElementById("container").appendChild(jump);
}
};
Where did I go wrong? Thank you. The div container has the background image that is placed "under" the created inner divs.
document.querySelectorAll returns an array of elements. You would need to loop through them individually.
var blocks = document.querySelectorAll("#container div");
var index = 0, length = blocks.length;
for ( ; index < length; index++) {
blocks[index].style.zIndex = 1;
}
If you are only looking for a single element you can also use document.querySelector which returns the first element it finds that matches the selector and you can work directly on it as you originally had in your code.

Faulty Logic in this image color equalization algorithm

Somewhere in my code, I seem to be doing something wrong and I cannot tell which part is going awry. I've printed to console the values I'm getting from the various arrays and it seems to match up. Then when I run the equalization function (a la Wikipedia-Histogram Equalization) my output image is close to total black. I was trying to interpret this guy's php into javascript just to test some stuff out and figured I did a decent job. But I'm not an expert.
The pertinent parts:
function imageLoaded(ev) {
element = document.getElementById("canvas1");
c = element.getContext("2d");
im = ev.target; // the image
// read the width and height of the canvas
width = element.width;
height = element.height;
// stamp the image on the left of the canvas:
c.drawImage(im, 0, 0);
// get all canvas pixel data
imageData = c.getImageData(0, 0, width, height);
w2 = width / 2;
var reds = new Array();
var greens = new Array();
var blues = new Array();
var freqR = new Array();
var freqG = new Array();
var freqB = new Array();
if (imageData){
buildHistograms(reds, greens,blues);
buildFrequencies(reds, greens, blues, freqR, freqG, freqB);
}
var alpha = 255/(w2*height);
// run through the image
for (y = 0; y < height; y++) {
inpos = y * width * 4; // *4 for 4 ints per pixel
outpos = inpos + w2 * 4;
for (x = 0; x < w2; x++) {
//reads pixel data(of img c)to each channel of rgb
r = imageData.data[inpos++];
g = imageData.data[inpos++];
b = imageData.data[inpos++];
a = imageData.data[inpos++];
//using histogram eqalization formula:
adjR = freqR[r]*alpha;
adjG = freqG[g]*alpha;
adjB = freqB[b]*alpha;
//assigns pixel data of output image
imageData.data[outpos++] = adjR;
imageData.data[outpos++] = adjG;
imageData.data[outpos++] = adjB;
imageData.data[outpos++] = a;
}
}
// put pixel data on canvas
c.putImageData(imageData, 0,0);
}
im = new Image();
im.onload = imageLoaded;
im.src = "Lenna.png";
function buildHistograms(reds,greens,blues){
//run through image building histogram
for (y=0; y < height; y++){
inpos = y * width *4;
for (x=0; x < w2; x++){
rd = imageData.data[inpos++];
g = imageData.data[inpos++];
b = imageData.data[inpos++];
a = imageData.data[inpos++];
// Add counts to our histogram arrays for each color.
reds.push(rd);
greens.push(g);
blues.push(b);
}
}
// Sort them by keys into order
reds.sort(function(a,b){return a-b});
greens.sort(function(a,b){return a-b});
blues.sort(function(a,b){return a-b});
}
function buildFrequencies(reds, greens, blues, freqR, freqG, freqB){
// Build frequency charts for all colors: takes REDS GREENS BLUES from buildHistograms and places them on top of each other accordingly
for(i=0; i<=255; i++){
sumR=0;
sumG=0;
sumB=0;
for(j=0; j<= i; j++){
if (reds[j]){sumR+=reds[j];}
if (greens[j]){sumG+=greens[j];}
if (blues[j]){sumB+=blues[j];}
}
freqR[i] = sumR;
freqG[i] = sumG;
freqB[i] = sumB;
}
}
Any help is appreciated, Thanks.
Looks like my build frequencies section was all wrong. I modified it in this way:
var len = reds.length;
for (j=0; j < len; j++) {
var rCurrVal = reds[j];
var gCurrVal = greens[j];
var bCurrVal = blues[j];
if (freqR.hasOwnProperty(rCurrVal)) {
freqR[rCurrVal] += 1;
} else {
freqR[rCurrVal] = 1;
}
if (freqG.hasOwnProperty(gCurrVal)) {
freqG[gCurrVal] += 1;
} else {
freqG[gCurrVal] = 1;
}
if (freqB.hasOwnProperty(bCurrVal)) {
freqB[bCurrVal] += 1;
} else {
freqB[bCurrVal] = 1;
}
}
for (i=0; i<255; i++){
if ($.inArray(i,reds)===-1){freqR[i]=0;}
if ($.inArray(i,greens)=== -1){freqG[i]=0;}
if ($.inArray(i,blues)=== -1){freqB[i]=0;}
if (i>0){
freqR[i]+=freqR[i-1];
freqG[i]+=freqG[i-1];
freqB[i]+=freqB[i-1];
}
}

I want to remove img tag on click of button from javascript

I have added here 2 functions moveoutid() for creating img tag on click of button and it addes image src to img tag to show image on webpage. and moveinid() for removing selected image from img tag.
function moveoutid() {
var sda = document.getElementById('availableFruits');
var len = sda.length;
var sda1 = document.getElementById('orderFruits');
for (var j = 0; j < len; j++) {
if (sda[j].selected) {
alert(baseUrl + "/img/" + sda.options[j].value + ".jpg");
var img1 = document.createElement('img').src = baseUrl + "/img /" + sda.options[j].value + ".jpg";
var di = document.getElementById('d');
di.appendChild(img1);
var tmp = sda.options[j].text;
var tmp1 = sda.options[j].value;
sda.remove(j);
j--;
var y = document.createElement('option');
y.text = tmp1;
try {
sda1.add(y, null);
} catch (ex) {
sda1.add(y);
}
}
}
}
function moveinid() {
var sda = document.getElementById('availableFruits');
var sda1 = document.getElementById('orderFruits');
var len = sda1.length;
for (var j = 0; j < len; j++) {
if (sda1[j].selected) {
di = document.getElementById('d');
img1.src = baseUrl + "/img/" + sda1.options[j].value + ".jpg";
//img.className="";
di.removeChild(img1);
var tmp = sda1.options[j].text;
var tmp1 = sda1.options[j].value;
sda1.remove(j);
j--;
var y = document.createElement('option');
y.text = tmp;
try {
sda.add(y, null);
} catch (ex) {
sda.add(y);
}
}
}
}
I want to remove selected img tag from div (means which ever image selected by user in dropdown list that image should be remove.)
Instead of removing the tag it sounds like you just need to show and hide that image.
document.getElementById('Image').style.visibility='visible';
If I understood correctly. Or you could even destroy the element removing it from the DOM.

Html5 canvas loading images with JCanvasScript

hello guys I want to load multiple images with JCanvasScript in html5 canvas, but I can't do it. I want to load images side by side in each row. for that I have function loadx(numX, numY) numX - is number of images in a row and numY is number of rows. for example loadX(5,4) or loadX(10,3) is giving me the same result only 1 image.
here is a code
<script>
function init(){
loadx(5, 4);
}
function loadx(numX, numY){
var numTotal = numX * numY;
var imgBMPs = [];
var sliceImg = new Image();
sliceImg.src = "abstract.jpg";
var sliceBmp;
var imgBmp = [];
imgBmp['width'] = sliceImg.width / numX;
imgBmp['height'] = sliceImg.height / numY;
imgBmp['row'] = 0;
imgBmp['y'] = 0;
sliceImg.onload = function(){
for (i = 0; i < numY; i++){
imgBmp['y'] = i * imgBmp['height'];
for (a = 0; a < numX; a++){
jc.start('canvas');
imgBmp = new jc.image(sliceImg, a * imgBmp['width'], imgBmp['y'], imgBmp['width'], imgBmp['height']);
imgBMPs.push(imgBmp);
jc.start('canvas');
}
}
}
}
</script>
when I tried to debug the code I found out something:
after this
sliceImg.onload = function(){
for (i = 0; i < numY; i++){
imgBmp['y'] = i * imgBmp['height'];
I added the code
alert (imgBmp['height']);
and when I refreshed the page First result was the number but other were "Undefined" so what is wrong?
Within your inner for loop you're reassigning the variable imgBmp to an instance of js.image. This means that the properties of the original object are lost by the time the loop iterates the second time.
Try updating your code as follows:
<script>
function init(){
loadx(5, 4);
}
function loadx(numX, numY){
var numTotal = numX * numY;
var imgBMPs = [];
var sliceImg = new Image();
sliceImg.src = "abstract.jpg";
var sliceBmp;
/*
// imgBmp is being used as an object not an array
// so the following syntax is usually preferred
var imgBmp = {
width: sliceImg.width / numx,
height: sliceImg.height / numy
}
// and to retrieve a property:
console.log(imgBmp.width);
*/
var imgBmp = [];
imgBmp['width'] = sliceImg.width / numX;
imgBmp['height'] = sliceImg.height / numY;
imgBmp['row'] = 0;
imgBmp['y'] = 0;
sliceImg.onload = function(){
for (i = 0; i < numY; i++){
imgBmp['y'] = i * imgBmp['height'];
for (a = 0; a < numX; a++){
jc.start('canvas');
// create a new variable to hold the instance of jc.image
// so the original object reference is preserved
var jcImage = new jc.image(sliceImg, a * imgBmp['width'], imgBmp['y'], imgBmp['width'], imgBmp['height']);
imgBMPs.push(jcImage);
//imgBmp = new jc.image(sliceImg, a * imgBmp['width'], imgBmp['y'], imgBmp['width'], imgBmp['height']);
//imgBMPs.push(imgBmp);
jc.start('canvas');
}
}
}
}
</script>

Categories

Resources