I have a web page that is going to display a number of images on an HTML5 canvas.
I am loading the images in a hidden section in the HTML first, before using JavaScript to draw them on the canvas, in order to speed up the amount of time is takes them to load and be rendered on the canvas.
Once all of the images have been drawn to the canvas, it must be possible to drag and drop them around the canvas. The purpose being that there will be four 'description buckets' also displayed on the canvas, and the user is required to drag each image to its corresponding description bucket.
Once I have loaded the images in the HTML, I want to create a JavaScript array to store them in while they're being accessed and manipulated by the JavaScript, i.e. I want to be able to manipulate them as if they are JavaScript images, although their sources will be HTML elements, not the direct source of the image.
I'm following the tutorial at: http://www.html5canvastutorials.com/labs/html5-canvas-animals-on-the-beach-game-with-kineticjs/ which does exactly what I want to do, except that the images are static. With my game, I will be providing a web form which the administrator will be able to use to change the images that are displayed depending on in what context they are using the game.
This is why where that tutorial has the code:
window.onload = function() {
var sources = {
beach: "beach.png",
snake: "snake.png",
snake_glow: "snake-glow.png",
snake_black: "snake-black.png",
lion: "lion.png",
lion_glow: "lion-glow.png",
lion_black: "lion-black.png",
monkey: "monkey.png",
monkey_glow: "monkey-glow.png",
monkey_black: "monkey-black.png",
giraffe: "giraffe.png",
giraffe_glow: "giraffe-glow.png",
giraffe_black: "giraffe-black.png",
};
loadImages(sources, initStage);
};
I want to change the sources to be those of the images that I have loaded in the hidden section of the HTML:
<section hidden>
<img id="startButton" src="images/startButton.png" alt="Start Button" width="179" height="180" href="javascript:drawLevelOneElements();"/>
<img id="building" src="images/assets/building.png" alt="Asset" />
<img id="chair" src="images/assets/chair.gif" alt="Asset" />
<img id="drink" src="images/assets/drink.gif" alt="Asset" />
<img id="food" src = "images/assets/food.gif" alt="Asset"/>
<img id="fridge" src = "images/assets/fridge.png" alt="Asset"/>
<img id="land" src = "images/assets/land.jpg" alt="Asset"/>
<img id="money" src = "images/assets/money.jpg" alt="Asset"/>
<img id="oven" src = "images/assets/oven.jpg" alt="Asset"/>
<img id="table" src = "images/assets/table.gif" alt="Asset"/>
<img id="van" src = "images/assets/van.jpg" alt="Asset"/>
<img id="burger" src = "images/expenses/direct/burger.png" alt="Direct Expense"/>
<img id="chips" src = "images/expenses/direct/chips.png" alt="Direct Expense"/>
<img id="drink" src = "images/expenses/direct/drink.jpg" alt="Direct Expense"/>
<img id="franchiseFee" src = "images/expenses/direct/franchiseFee.jpg" alt="Direct Expense"/>
<img id="wages" src = "images/expenses/direct/wages.jpg" alt="Direct Expense"/>
<img id="admin" src = "images/expenses/indirect/admin.jpg" alt="Indirect Expense"/>
<img id="cleaners" src = "images/expenses/indirect/cleaners.gif" alt="Indirect Expense"/>
<img id="electricity" src = "images/expenses/indirect/electricity.gif" alt="Indirect Expense"/>
<img id="insurance" src = "images/expenses/indirect/insurance.jpg" alt="Indirect Expense"/>
<img id="manager" src = "images/expenses/indirect/manager.jpg" alt="Indirect Expense"/>
<img id="rates" src = "images/expenses/indirect/rates.jpg" alt="Indirect Expense"/>
<img id="training" src = "images/expenses/indirect/training.gif" alt="Indirect Expense"/>
<img id="water" src = "images/expenses/indirect/water.gif" alt="Indirect Expense"/>
<img id="burger" src = "images/income/burger.png" alt="Income"/>
<img id="chips" src = "images/income/chips.png" alt="Income"/>
<img id="drink" src = "images/income/drink.jpg" alt="Income"/>
<img id="creditors" src = "images/liabilities/creditors.gif" alt="Liability"/>
<img id="electricity" src = "images/liabilities/electricity.png" alt="Liability"/>
<img id="food" src = "images/liabilities/food.jpg" alt="Liability"/>
<img id="hirePurchase" src = "images/liabilities/hirePurchase.jpg" alt="Liability"/>
<img id="loan" src = "images/liabilities/loan.png" alt="Liability"/>
<img id="overdraft" src = "images/liabilities/overdraft.jpg" alt="Liability"/>
<img id="payeTax" src = "images/liabilities/payeTax.jpg" alt="Liability"/>
<img id="tax" src = "images/liabilities/tax.jpg" alt="Liability"/>
</section>
but I'm not sure how to reference the HTML images. I tried doing it in a similar way to the way you would reference the images in JavaScript directly from their sources:
window.onload = function(){
var sources = {
asset1: document.getElementById("building");
asset2: document.getElementById("chair");
}
}
but when I loaded the page in the browser, my canvas was no longer displayed.
So far I have managed to get the canvas displaying, with one image that can be dragged and dropped around the canvas using this code:
var canvasImage = new Kinetic.Image({
image: imageObj,
width: 50,
height: 50,
// puts the image in teh middle of the canvas
x: stage.getWidth() / 2 - 50 / 2,
y: stage.getHeight() / 2 - 50 / 2,
draggable: true
});
var imageObj = new Image();
imageObj.onload = function() {
drawImage(this);
};
imageObj.src = 'images/assets/building.png';
but obviously the problem with this is that if I was to provide the administrator with a form where they could change the src of the image that's drawn from 'building.png' to some other image file, I wouldn't be able to replace the line that's loading the 'building' image in the hidden section of my HTML with a line to now load the new image instead.
Does anyone know how I can reference the HTML images from within the JavaScript?
Edit 10/12/2012 # 21:00
I tried changing the code to:
var sources = {
asset1: document.getElementById("building"),
asset2: document.getElementById("chair")
}
but my canvas still wasn't displayed when viewing the page in the browser. I also tried that with a comma after the second line, but the canvas wasn't displayed.
Edit 10/12/2012 # 22:55
I now have this function:
window.onload = function(){
var sources = {
asset1: document.getElementById("building").src,
asset2: document.getElementById("chair").src,
};
loadImages(sources, drawImage);
};
and try to draw the image on the canvas with this code:
var imageObj = new Image();
imageObj.onload = function() {
drawImage(this);
};
imageObj.src = sources.asset1;
but for some reason, this has again stopped the canvas from displaying in the browser... The only thing I've changed since it was displaying in the browser is the line: imageObj.src = sources.asset1;
Your code
var sources = {
asset1: document.getElementById("building");
asset2: document.getElementById("chair");
}
produces a syntax error. Your property declarations should end with commas, not semicolons (as you did correctly in your first object declaration).
The reason your canvas disappeared when you tried that code is because the script interpreter halted on the syntax error.
EDIT:
If you want to recreate your first object (the one with image URL strings) using image elements from the DOM, get the src property of each element:
var sources = {
asset1: document.getElementById("building").src,
asset2: document.getElementById("chair").src
}
Related
I have a static webpage with over 50-100 images and I want to create a separate container to show each image as a thumbnail. When clicking on the image, it should bring you to the image. I'm having issues when you click on the image and it should bring you to that image on the page.
// loop through img elements
$('.img-class').each(function(){
// create new image object
image = new Image();
// assign img src attribute value to object src property
image.src = $(this).attr('src');
var xx = document.getElementById('gallery');
xx.insertAdjacentHTML('beforeend', '<img src="'+ image.src +'"/>');
});
Sample of the HTML:
<div id='mydata'>
<img src='x.jpg'/>
<img src='1.jpg'/>
<img src='2.jpg'/>
<img src='3.jpg'/>
</div>
<div id='gallery'>
<img src='x.jpg' width='50' height='50'/>
<img src='1.jpg' width='50' height='50'/>
<img src='2.jpg' width='50' height='50'/>
<img src='3.jpg' width='50' height='50'/>
</div>
The gallery is generated when the page loads.
I have a site with many different gallery categories that display a smaller thumbnail size until the screen width is below 1200px, after which I would like to display the full size instead.
The images are displayed like so:
<section class="gallery category1">
<img id="cat1img1" src="cat1/small/img-1.jpg" alt="blah">
<img id="cat1img2" src="cat1/small/img-2.jpg" alt="blah">
etc...
</section>
<section class="gallery category2">
<img id="cat2img1" src="cat2/small/img-1.jpg" alt="blah">
<img id="cat2img2" src="cat2/small/img-2.jpg" alt="blah">
etc...
</section>
And all I want to do is use a JS media query with some jQuery to remove the "small/" from each tag without listing every single img so they can be freely added and removed without modifying the code again.
This is what I've tried but it's not changing the img url, though it does trigger my size change check:
function galleryBreak(x) {
if (x.matches) {
$('.gallery').children('img').attr('src').replace('/small','')
console.log('size change check');
};
};
var x=window.matchMedia('(max-width: 1200px)')
galleryBreak(x)
x.addListener(galleryBreak)
You have multiple (2) galleries and multiple images. You need to iterate over all images for all galleries. Something like this
function changeImagePaths(theGallery) {
var images = theGallery.querySelectorAll('img');
images.forEach( image => {
console.log('Path before: ', image.src)
image.src = image.src.replace('/small','')
console.log('Path AFTER: ', image.src)
});
};
var x=window.matchMedia('(max-width: 1200px)')
var myGalleries = document.querySelectorAll('.gallery')
myGalleries.forEach( gallery => {
if(x.matches) {
changeImagePaths(gallery)
}
});
<section class="gallery category1">
<img id="img1" src="cat1/small/img-1.jpg" alt="blah">
<img id="img2" src="cat1/small/img-2.jpg" alt="blah">
</section>
<section class="gallery category2">
<img id="img1" src="cat2/small/img-1.jpg" alt="blah">
<img id="img2" src="cat2/small/img-2.jpg" alt="blah">
</section>
JsFiddle to play with here
Now all of that said, if you can change the HTML please use Responsive images which will show you all you need can be set right in the image tag like:
<img srcset="elva-fairy-320w.jpg,
elva-fairy-480w.jpg 1.5x,
elva-fairy-640w.jpg 2x"
src="elva-fairy-640w.jpg"
alt="Elva dressed as a fairy">
add resize event listener on window so that on each window / browser resize this event will be fired
const galleryBreak = () => {
if (window.matchMedia('(max-width: 1200px)').matches) {
const images = document.querySelectorAll('.gallery img');
Array.from(images).forEach(img => {
const imgSrc = img.src.replace('/small', '');
img.src = imgSrc;
console.log(imgSrc);
});
}
};
window.addEventListener('resize', galleryBreak);
I want to show div with an image, it's name, it's size and it's download link with jquery.
for that, I have made below code
var image = 'image/example.png'
$('#download').attr("href", result2);
$('.image').attr("src", result2);
var name = result2.replace('image/', '');
$('.name').text(name);
$('.filename').css('display','block');
<div class="filename" style="display: none;">
<img src="" class="image" width="100PX" height="100PX">
<b class="name">example.png</b>
<span class="size"></span>
DOWNLOAD
</div>
and my image is
everything is working fine except image size I don't know how can I get image size because when I was searching to get image size with it's MB, KB or in bytes with jquery it shows me a result in this formate $("#selector")[0].files[0].size but in my case, there is no files[0] is available so how can I find image size?
You can use fetch to get the reponse size. Since you make a request with an image path, the response size will points to the image size.
fetch($('img').prop('src')).then(function (response) {
console.log('size:', response.headers.get("content-length"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">
Another way to get the image width/height is: Using Image class:
var image = new Image();
image.onload = function () {
console.log('width:', this.width);
console.log('height:', this.height);
console.log('more information about this image:');
console.dir(this);
};
image.src = $('img').prop('src');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">
On my website I have three images 1.png, 2.png and 3.png. When I click on 1.png, I want the animated gif 1a.gif to be loaded and shown/updated in the img tag located in <div id="container">. When I click on 2.png, 2a.gif should be displayed (while 1a.gif vanishes) and so on... This is my code:
<html>
<body>
<div>
<img src="1.png" onclick="document.getElementById('img').src = '1a.gif'" />
<img src="2.png" onclick="document.getElementById('img').src = '2a.gif'" />
<img src="3.png" onclick="document.getElementById('img').src = '3a.gif'" />
</div>
<div id="container">
<img id="img" src="1a.gif" />
</div>
</html>
</body>
It is working, however unreliable (tested with firefox and chrome)! When I refresh the html page and click on 1.png, than on 2.png ... suddendly at one point only the first frame of the animated gif is shown. I have to click on the same image (1,2 or 3.png) again in order to make the gif run. Why? I am looking for a light weight javascript solution without jquery. I am just asking myself why the gif is not played properly once I click on the image.
As a side note: It would be nice to show a loading image while the gif (5 MB) is loading. I failed to achive that using css:
#container {background:url('loading.png') no-repeat; }
In this case the loading image doesn't show up at all. Probably because I am updating directly from one (e.g. 1a.gif) to another (e.g. 2a.gif).
Showing it right before loading the gif did not help as well:
<img src="1.png" onclick="document.getElementById('img').src = 'loading.png';
document.getElementById('img').src = '1a.gif'" />
There are many ways of implementing this kind of thing, but to keep in line with how you're doing it, you'll want to hook into the onload event of the img.
Note that in this snippet, I don't have access to your GIFs, so I'm using the dummyimage.com service, which is pretty fast, so you don't see the "loading" for very long.
window.onload = function() {
var img = document.getElementById('img');
var container = document.getElementById('container');
var showImage = function showImage() {
img.style.display = "inline";
container.style.backgroundImage = "";
};
img.addEventListener('load', showImage);
img.addEventListener('error', showImage);
var thumbs = document.getElementsByClassName('thumb');
for (var i = 0, z = thumbs.length; i < z; i++) {
var thumb = thumbs[i];
var handler = (function(t) {
return function clickThumb() {
container.style.backgroundImage = "url('https://dummyimage.com/500x500/000/fff.gif&text=loading')";
img.style.display = "none";
img.src = t.dataset['image'];
};
})(thumb);
thumb.addEventListener('click', handler);
}
};
<div>
<img src="1.png" class="thumb" data-image="https://dummyimage.com/500x200/000/fff.gif" />
<img src="2.png" class="thumb" data-image="https://dummyimage.com/200x200/000/fff.gif" />
<img src="3.png" class="thumb" data-image="https://dummyimage.com/500x500/000/fff.gif" />
</div>
<div id="container">
<img id="img" class="main" />
</div>
This happens bacause the second img is not loaded yet!
I suggest you to put the 2 img in 2 different divs and the use javascript to hide/show the entire div!
I have a quick issue that I need help with and hoping a fresh set of eyes can pinpoint my issue. I have a photo gallery and I want to display a larger image of the thumbnail when it is clicked. The thumbnails images show up fine at the bottom but are not clickable and the main (or larger image) does not show up. I am using an external .js file. I will upload the HTML also, and maybe some one can point me in the right direction and help me understand what I am overlooking.
<!doctype html>
<html>
<head>
<title>Photo Gallery Final Project</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" href = "gallery.css">
</head>
<body>
<div class = "main">
<div class = "wrapper">
<div id = "largeImage">
<img src = "images/machine_1_big.jpg" alt = "machining image" width = "920" height = "400" id = "myImage" class = "border"/>
</div>
<div class = "thumbnail">
<img src="machine_1.jpg" alt = "machining lathe" id="machine_1"/>
<img src="machine_2.jpg" alt = "machining lathe" id="machine_2"/>
<img src="machine_3.jpg" alt = "machining lathe" id="machine_3"/>
<img src="machine_4.jpg" alt = "machining lathe" id="machine_4"/>
<img src="machine_5.jpg" alt = "machining lathe" id="machine_5"/>
<img src="machine_6.jpg" alt = "machining lathe" id="machine_6"/>
</div>
</div>
</div>
<script src = "gallery.js"></script>
</body>
</html>
//this will load the gallery in the browser and enable the gallery function
//window.onload = gallery;
//gallery funtion declared
function gallery(){
//variable allGalleryImages created. This is where all the images will be held
var allGalleryImages = document.images;
//for loop declared for the image array
for(var i = 0; i < allGalleryImages.length; i++){
if(allGalleryImages[i].id.indexOf("small") > -1){
//this will add a listener to the thumb images
allGalleryImages[i].onclick = imgChanger;
}
}
}
//this is the image changer function
function imgChanger(){
//this will change the src attribute value of the large image.
//document.getElementById('myImage').src ="images/"+this.id+"_big.jpg";
document.getElementById('myImage').src = " " + this.id +"_big.jpg";
}
I used JQuery. Did not have to change your HTML. And there is no reason to make and array of all the thumbnails.
$(document).ready(function() {
$(".thumbnail img").on("click", function() {
imgChanger($(this).attr("src"));
})
//this is the image changer function
function imgChanger(theSRC) {
//this will change the src attribute value of the large image.
//document.getElementById('myImage').src ="images/"+this.id+"_big.jpg";
var beforeJPG = theSRC;
console.log(beforeJPG);
beforeJPG = beforeJPG.substring(0, beforeJPG.length-4);
console.log(beforeJPG + "_big.jpg");
$("myImage").attr("src", beforeJPG + "_big.jpg");
}
})
Fiddle: https://jsfiddle.net/6v8arhp2/
Get the src of the clicked image
Chop off ".jpg"
Add "images/" to the front, add "_big.jpg" to the back
Change src of #myImage
** Of course your images are not inside JSFiddle so you cannot see it work, but the console logs show the transformation.