Displaying one image in multiple locations - javascript

Disclaimer upfront: I'm still very new to JavaScript. (And to programming in general, for that matter.)
So, I'm trying to create an interface that would display an image in multiple aspect ratios, when cropped by object-fit: cover. I'd like to see several aspect ratios side-by-side and be able to test different images as well.
I'm using JavaScript's File API to avoid uploading/downloading. It's also worth noting that I'm doing everything on Google Apps Script so it can be an easily accessible web app.
Right now, I have the <img> in a <div> so I can use replaceChild. That's the only way I've been able to get it to work. You can see it here on CodePen. This is the function I've been using:
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
var placehold = document.getElementById('userImg');
document.getElementById('userImageDiv').replaceChild(img, placeHold);
}
img.id = "userImg";
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
What I've tried:
I tried getting the img.onload function to append img twice:
var placeholdTwo = document.getElementById('imgTwo');
document.getElementById('imageTwoDiv').replaceChild(img, placeholdTwo);
But it only displayed in imgTwo - I'm guessing because the function only creates one FileReader.
I also tried reading the image in one location, then copying it's src to additional locations, but no luck there:
function repeatImg(){
var repeatImage = document.getElementById('userImg').src;
document.getElementById('imageOne').src = repeatImage;
document.getElementById('imageTwo').src = repeatImage;
}
Then, I tried making multiples of the whole handleImage function and calling them all with an event listener, but that didn't work either.
Is there any way to accomplish this?

Simply wrap the original file object, which is a blob, and set that as source. This way you avoid adding up memory usage and base64 encoding/decoding overheads as with a Data-URL - there's no need to create an intermediate image element either - just update the src on the existing ones:
document.querySelector("input").onchange = handleImage;
function handleImage() {
var url = URL.createObjectURL(this.files[0]);
document.getElementById('userImg').src =
document.getElementById('imageOne').src =
document.getElementById('imageTwo').src = url;
}
<label>Select an image: <input type=file></label>
<img id=userImg>
<img id=imageOne>
<img id=imageTwo>

Looking at the linked pen, repeatImg does not get called by the userImgDiv change event listener.
Calling repeatImg() at the end of img.onload works for me.
img.onload = function(){
var placeHold = document.getElementById('userImg');
document.getElementById('userImageDiv').replaceChild(img, placeHold);
repeatImg();
}
CodePen.

I think perhaps I'm missing something, but why not just set the image sources in your img.onload method?
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
var placehold = document.getElementById('userImg');
document.getElementById('userImageDiv').replaceChild(img, placeHold);
document.getElementById('imageOne').src = img.src;
document.getElementById('imageTwo').src = img.src;
}
img.id = "userImg";
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}

You're only using one Image. I would do something like this instead:
/* external.js */
//<![CDATA[
var doc, bod, M, I, Q, S, old = onload; // for use on other loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; bod = doc.body;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
Q = function(selector, withinElement){
var w = withinElement || doc;
return w.querySelectorAll(selector);
}
S = function(selector, withinElement){
var w = withinElement || doc;
return w.querySelector(selector);
}
I('form').onsubmit = function(){
return false;
}
// you can put the below code on another page onload if you want
var up = I('upload'), out = I('out'), reader = new FileReader;
up.onchange = function(){
reader.onload = function(){
var img0 = M('img'), img1 = M('img');
img0.src = img1.src = this.result; out.innerHTML = '';
out.appendChild(img0); out.appendChild(img1);
}
reader.readAsDataURL(this.files[0]);
}
}
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#ccc; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='form' name='form'>
<input id='upload' name='upload' type='file' />
</form>
<div id='out'></div>
</div>
</body>
</html>

Related

Can't retrieve the correct image size using javascript

Ok, first time posting a question so I hope I do everything by the book.
I wanted to use javascript to retrieve and display the width/height of an image that the user picks using an Input button. But it's a hot day here and I can feel my brain just going round in circles.
Using this script I get it to display the image and the width (or so I thought). I try to select an image which is 180px wide but my script returns the number 16. Other images either returns 16 or other arbitrary numbers.
EDIT: Different browsers return different numbers.
What am I displaying and what am I missing to get it right?
This is my HTML:
<head>
<title>Image size calculator</title>
<!-- Normalize.css -->
<link rel="stylesheet" type="text/css" href="normalize.css">
<!-- Custom Styles -->
<link rel="stylesheet" type="text/css" href="style.css">
<!--[if IE]>
<script
src="https://github.com/aFarkas/html5shiv/blob/master/src/html5shiv.js">
</script>
<![endif]-->
</head>
<body>
<h1>Vilken storlek har min bild?</h1>
<p><em>Supported formats are: BMP/CUR/GIF/ICO/JPEG/PNG/PSD/TIFF/WebP/SVG/DDS</em></p><br><br>
<form>
<input type="file" onchange="readURL(this);">
<br><br>
<img id="imageDisplay" src="#" />
<label id="imageSize">Bilden är: </label>
</form>
<!-- How to load jQuery.
1. Load the CDN version (internet)
2. If fail, load the installed (local) -->
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="js/jquery-3.3.1.js"><\/script>');</script>
<script src="js/script.js"></script>
</body>
And this is the code in my script.js file:
function readURL(input) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageDisplay')
.attr('src', e.target.result)
.width(this.width)
.height(this.height);
};
reader.readAsDataURL(input.files[0]);
var imgWidth = $("#imageDisplay").width();
$("#imageSize").append(imgWidth);
}
EDIT 2: Thanks for all the solutions. I tried out Scott's (which made me smack my forehead and say 'duh' when I read it). It seems I was on the right track as my suspicion was that the image wasn't fully loaded. I just couldn't get the code for checking that right. Sometimes you need a little push in the right direction. :)
You are attempting to get the size immediately after setting the src and it hasn't had enough time for the image to finish loading by then. You need to set up a load event handler for the image in addition to the one for the reader.
var imgWidth = null;
var imgHeight = null;
// The image needs a load callback that won't fire until the image
// is finished downloading.
$('#imageDisplay').on("load", function(){
// Now, it's safe to get the width and height >
imgWidth = this.width;
imgHeight = this.height;
$("#imageSize").append(imgWidth);
});
function readURL(input) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageDisplay').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
You should use HTMLImageElement.naturalWidth and HTMLImageElement.naturalHeight instead of just image.width and image.height.
While the former returns the original/intrinsic width or height of the image, the latter will return the dimensions of the image as displayed. That means that if you are resizing it with CSS, you will get the values based on that.
Also, the image itself also has an image.onload event you should listen to in order to access its properties once it has finished loading. Otherwise, you might access them before and get incorrect values.
Anyway, image.naturalWith and image.naturalHeight are available before the onload event is triggered, so you might try to get them instead, but in order to have a reliable solution, you need to implement polling using WindowOrWorkerGlobalScope.setInterval.
You can check this out in this example:
const input = document.getElementById('input');
const button = document.getElementById('button');
const image = document.getElementById('image');
const naturalSize = document.getElementById('naturalSize');
const displaySize = document.getElementById('displaySize');
let intervalID = null;
function updateSizeLabels() {
naturalSize.innerText = `ORIGINAL SIZE: ${ image.naturalWidth } × ${ image.naturalHeight }`;
displaySize.innerText = `DISPLAY SIZE: ${ image.width } × ${ image.height }`;
};
function changeImage(src) {
console.clear();
// Reset src so that you don't get the previus dimensions
// if you load more than one image:
image.src = '';
image.src = src;
// Solution with polling:
// We try to get the dimensions just after setting src:
const alreadyAvailable = pollNaturalDimensions();
// Polling only needed if the dimensions are not there yet:
if (!alreadyAvailable) {
// Just in case we already have a setInterval running:
clearInterval(intervalID);
// Every 10ms, we check again if naturalWidth is there:
intervalID = setInterval(pollNaturalDimensions, 10);
}
}
function pollNaturalDimensions() {
if (image.naturalWidth) {
console.log('Dimensions already available.');
// Stop polling:
clearInterval(intervalID);
// You can display the dimensions already:
updateSizeLabels();
return true;
}
}
// Solution with onload:
// This will update the size labels everytime an image is loaded:
image.onload = () => {
console.log('Image loaded.');
updateSizeLabels();
};
input.onchange = () => {
const reader = new FileReader();
reader.onload = (e) => changeImage(e.target.result);
reader.readAsDataURL(input.files[0]);
}
button.onclick = (e) => {
e.preventDefault();
changeImage(image.src === 'http://www.traversecityfilmfest.org/wp-content/uploads/2017/07/Baby-driver-gif.gif' ? 'https://thumbs.gfycat.com/BleakTenderBarb-small.gif' : 'http://www.traversecityfilmfest.org/wp-content/uploads/2017/07/Baby-driver-gif.gif');
};
body {
padding: 0 0 45px;
}
body,
input,
button {
font-family: monospace;
}
.as-console-wrapper {
max-height: 45px !important;
}
#image {
max-width: 200px;
max-height: 200px;
margin: 16px 0 0;
}
<h1>Select an image to see its dimensions:</h1>
<form>
<input id="input" type="file">
<button id="button">Load Remote Image</button>
</form>
<img id="image" />
<p id="naturalSize"></p>
<p id="displaySize"></p>
Note, that when working with local images, the image.onload solution might return the dimensions before the polling one. When testing it on my Mac, they seem to be head-to-head. However, if you try loading remote images, especially big ones and/or on slow networks, the polling solution would make more sense.
I would suggest restructuring your code like so, so that your image loads before you set the width:
function readURL(input) {
var reader = new FileReader();
var imgWidth;
reader.onload = function (e) {
$('#imageDisplay')
.attr('src', e.target.result)
.width(this.width)
.height(this.height);
imgWidth = $("#imageDisplay").width();
};
reader.readAsDataURL(input.files[0]);
$("#imageSize").append(imgWidth);
}
A simple approach would be
var img = new Image();
img.onload = function(){console.log(img.width,img.height)}
img.src = 'url'
As correctly pointed out by LGSon, you have to wait for onLoad.
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
}
}
clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element, excluding margin and border. So this will get the actual dimensions of the visible image.
var img = document.getElementById( 'imageDisplay' );
var width = img.clientWidth;
var height = img.clientHeight;
If you are requesting image sizes you have to wait until they load or you will only get zeroes:
Example:
var img = new Image();
img.onload = function() { console.log(this.width + ' x ' + this.height ) }
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

how to cache favicon javascript

I'm trying to cache my favicon image just like any other image, but I'm not seeing it in the cache, nor getting my confirmation console.log, nor seeing it when I disconnect from the internet (basically it is not caching).
I want to cache it so I can access it offline, so I can dynamically change the icon if the internet disconnects.
My html:
<link id="favicon" rel="icon" type="image/png" src="assets/favicon-red-16x16.ico.png">
My js:
// cache images
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
console.log('caching image...')
var img = new Image();
img.onload = function() {
console.log('image cached')
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.src = array[i];
}
}
preloadImages(["../assets/favicon-green-16x16.ico.png", "../assets/favicon-red-16x16.ico.png"]);
question: Is it possible to cache the favicon client side? Is there another way to store it locally?
if i convert to base64 how do I store and grab it from local storage?
ps. using Chrome latest
<___ UPDATE ___>
Though the question is technically answered, How can I do this two store 2 (more than one) base64 image? I can't figure out how to draw 2 onto a canvas or 2 canvases.
Try this code pal.
You can hide iconImage img element. The other img tag i have used, is for testing only, so you can remove it.
<!DOCTYPE html>
<html>
<link id="favicon" rel="icon" href="img_the_scream.jpg" />
<body>
<img id="iconImage" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">
<br />
<img id="img" width="220" height="277"/>
<script>
function onLoadHandler() {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("iconImage");
var base64Image = localStorage.getItem("lsFavicon");
var favicon = document.getElementById("favicon");
var img2 = document.getElementById("img");
if (base64Image == null && document.navigator.onLine) {
ctx.drawImage(img, 0, 0);
base64Image = canvas.toDataURL();
localStorage.setItem("lsFavicon", base64Image);
favicon.setAttribute("href", base64Image);
}
else if (base64Image != null) {
favicon.setAttribute("href", base64Image);
img2.setAttribute("src", base64Image);
}
}
window.onload = onLoadHandler;
</script>
</body>
</html>

HTML5/Javascript Image loading method & passing to variable

I have some code for loading images.
var assets = {
total:0,
success:0,
error:0
};
var stillLoading = true;
var img = {};
function LoadImage(name, path){
var toLoad = new Image();
toLoad.src = path;
assets.total++;
toLoad.addEventListener("load", function(){
assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
}, false);
toLoad.addEventListener("error", function(){
assets.error++;
}, false);
};
function Loading(){
if (assets.success == assets.total){
if (stillLoading){
console.log("All assets loaded. Starting game.");
};
stillLoading = false;
return false;
}else{
stillLoading = true;
return true;
};
};
May still be inefficient, and ugly since I'm new to practicing javascript, open to suggestions. It loads the image and tells the main program when all the assets have finished loading through the function Loading(), and then adds the image to the object img.
I've been using this for a while now for my images, and it works.
For example, if I did.
LoadImage("Car", "imageOfCar.png");
ctx.drawImage(img.Car, 0, 0);
this would draw the image just fine to the canvas.
However, when I assign another variable the image, which for various reasons I want to do, such as assigning images to objects. e.g.
var secondCar = img.Car
then try to draw it.
ctx.drawImage(secondCar, 0, 0);
I get this error.
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'
If it works for the initial variable, it should act the same way towards another variable that has just been assigned the exact same thing. So why is it am I getting this error?
If I was to load the image the typical way that doesn't check if it's finished loading.
img.Car = new Image();
img.Car.src = "imageOfCar.png";
secondCar = img.Car;
ctx.drawImage(secondCar);
This would work.
The behaviour here is a bit confusing, could someone explain to me what is happening, and perhaps suggest a way to fix it?
EDIT: Just to clarify.
This is the html file, called index.html.
<!DOCTYPE html>
<head>
<title>HTML5 Game Base</title>
<link rel = "stylesheet" type = "text/css" href = "styles.css">
</head>
<body>
<canvas id="screen" width="270" height="480" style="border:1px solid #000000;"></canvas>
<script src = "script.js"></script>
</body>
</html>
The canvas is set up as screen. All the javascript code I've displayed above takes place within script.js which is called in index.html.
This is how screen is called within the script.js.
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
This is what ctx.drawImage() is referencing.
I realize this won't be the most helpful answer, but I tinkered around with your code a little. This is what I used:
<!DOCTYPE html>
<head>
<title>HTML5 Game Base</title>
</head>
<body>
<canvas id="screen" width="270" height="480" style="border:1px solid #000000;"></canvas>
<script>
var stillLoading = true;
var img = {};
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
assets = {};
assets.total = 0;
function LoadImage(name, path){
var toLoad = new Image();
toLoad.src = path;
assets.total++;
toLoad.addEventListener("load", function(){
//assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
}, false);
toLoad.addEventListener("error", function(){
assets.error++;
}, false);
}
</script>
</body>
</html>
Then in Chrome's console I typed
LoadImage("Car", "map.png");
LoadImage("un", "Untitled.png");
ctx.drawImage(img.Car, 0, 0);
ctx.drawImage(img.un, 0, 0);
and get the expected result of images loading in the canvas. Even when assigning one of the img images to a new variable, this works as expected.
var second = img.Car
ctx.drawImage(second, 0, 0)
It appears everything is working fine when run manually, so my guess would be timing. When are you running these commands? Are they in the js file or from the console?
It would appear your LoadImage function is fine. Sorry this is not super helpful, but hopefully will help you rule out where not to look for the problem.
One approach could be to utilize Promise , as load event of new Image is asynchronous secondCar could be undefined when used as parameter within setInterval, e.g., load event of img may not be complete when var secondCar = img.Car applied after call to LoadImage; also added variable reference for setInterval for ability to call clearInterval() if needed
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var interval = null;
var assets = {
total: 0,
success: 0,
error: 0
};
var stillLoading = true;
var img = {};
function LoadImage(name, path) {
return new Promise(function(resolve, reject) {
var toLoad = new Image();
assets.total++;
toLoad.addEventListener("load", function() {
assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
// resolve `img` , `assets` object
resolve([img, assets])
}, false);
toLoad.addEventListener("error", function() {
assets.error++;
reject(assets)
}, false);
toLoad.src = path;
})
};
function Loading() {
if (assets.success == assets.total) {
if (stillLoading) {
console.log("All assets loaded. Starting game.");
};
stillLoading = false;
return false;
} else {
stillLoading = true;
return true;
};
};
var promise = LoadImage("Car", "http://pngimg.com/upload/audi_PNG1736.png");
promise.then(function(data) {
// `data` : array containing `img` , `assets` objects
console.log(data);
var secondCar = data[0].Car;
interval = setInterval(function() {
if (!(Loading())) {
ctx.drawImage(secondCar, 0, 0);
};
}, 1000 / 60);
});
<canvas id="screen" width="1000" height="700" style="border:1px solid #000000;"></canvas>
Solved. Turns out it was a timing issue. In the example I gave, when secondCar is assigned img.Car, img.Car had not yet loaded.
Instead I created a new function called Initialise(), and called it from within Loading(). So from now on I would just have to initialise all my variables that may require images from within Initialise(). This way, variables can only be assigned images after they've loaded.
New Code:
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var assets = {
total:0,
success:0,
error:0
};
var stillLoading = true;
var img = {};
function LoadImage(name, path){
var toLoad = new Image();
toLoad.src = path;
assets.total++;
toLoad.addEventListener("load", function(){
assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
}, false);
toLoad.addEventListener("error", function(){
assets.error++;
}, false);
};
function Loading(){
if (assets.success == assets.total){
if (stillLoading){
console.log("All assets loaded. Starting game.");
Initialise();
};
stillLoading = false;
return false;
}else{
stillLoading = true;
return true;
};
};
LoadImage("Car", "http://pngimg.com/upload/audi_PNG1736.png");
function Initialise(){
window.secondCar = img.Car;
};
setInterval(function(){
if (!(Loading())) ctx.drawImage(secondCar, 0, 0);
}, 1000/60);
Works now, thanks for the help although I ended up solving it myself. I would still appreciate any tips on how to improve it. Or knowing that I'm new to javascript, any nitpicks to help me conform to javascript conventions.

how to load bitmap using easeljs?

I am trying to load bitmap using easeljs but its not working, please help me.
function init() {
canvas = document.getElementById("testCanvas");
context = canvas.getContext("2d");
stage = new createjs.Stage(canvas);
var image = new Image();
image.src = "assets/puli.png";
var container = new createjs.Container();
stage.addChild(container);
bitmap = new createjs.Bitmap(image);
container.addChild(bitmap);
createjs.Ticker.addEventListener("tick", tick);
}
function tick(event) {
if (update) {
update = false; // only update once
stage.update(event);
}
}
You have to load your images using the LoadQueue Class form EaselJs:
take a look at this--> http://www.createjs.com/Docs/PreloadJS/classes/LoadQueue.html
var queue = new createjs.LoadQueue(true);
queue.addEventListener("fileload",onFileLoaded.bind(this));
var manifest = getManifest();
queue.loadManifest(manifest);
onFileLoaded = function(evt)
{
var item = evt.item;
var type = evt.type;
}
getManifest = function()
{
var manifest = [
{src:"/images/yourimage.png", id:"myimage"}
];
return manifest;
}
//create images
var myimage = new createjs.Bitmap(images.myimage);
#CMS is right that preloading the content helps -- the issue you are seeing is likely that the image is not loaded when you update the stage, and it is only updating once.
You can use your approach in the original question, as long as you update the stage once the image is loaded. You can do this simply by waiting for a load event from the image. Something like this:
image.onload = function() {
update = true;
// OR
stage.update();
}
Using PreloadJS is a better approach for a larger app, since it gives you way more control of when assets are loaded, etc -- but its not necessary to get your code working.
I feel your pain.
Try this - I put the addChild and stage update in the onload event.
Works for me.
var stage, rect, img, greenRect;
function init() {
stage = new createjs.Stage("demoCanvas");
rect = new createjs.Shape();
img = new Image();
img.src = 'green.jpg';
img.onload = handleImageLoad;
}
function handleImageLoad(event) {
greenRect = new createjs.Bitmap(img);
stage.addChild(greenRect);
greenRect.x = 100;
greenRect.y = 100;
stage.update();
}
I got this code from YouTube, and it works
<!DOCTYPE html>
<html>
<head>
<script src="easeljs.js"></script> <!==load the EaselJS library==>
<script>
//this sample displays a bitmap file
var stage, img, map; //declare global variables
function init() {
//this function is registered in the html body tag
stage = new createjs.Stage("demoCanvas"); //create a Stage object to work with the canvas element
img = new Image(); //create an Image object, then set its source property
img.src="my_photo.jpg";
img.onload = handleImageLoad //register a handler for the onLoad event
}
function handleImageLoad(event) {
//this function runs when the onload event completes
map = new createjs.Bitmap(img); //create a Bitmap object, then set properties
map.x =50;
map.y =50;
stage.addChild(map); //add the Bitmap object as a child of the stage, then update the stage
stage.update();
}
</script>
</head>
<body onload="init();">
<!==add a canvas tag==>
<canvas id="demoCanvas" width="640" height="480"></canvas>
</body>
</html>
This code works when the PreloadJS library is sourced
<!DOCTYPE html>
<html>
<head>
<script src="EaselJS/lib/easeljs.js"></script> <!==load the EaselJS library==>
<script src="PreloadJS/lib/preloadjs.js"></script> <!==load the PreloadJS library==>
<script>
//this sample displays a bitmap file
var stage; //declare global variables
var img;
var map;
var queue;
function init() {
//this function is registered in the html body tag
stage = new createjs.Stage("canvas"); //create a Stage object to work with the canvas element
img = new Image(); //create an Image object, then set its source property
img.onload = handleImageLoad //register a handler for the onLoad event
queue = new createjs.LoadQueue();
queue.addEventListener('complete', handleImageLoad);
queue.loadManifest([
id="img", img.src="my_photo.jpg"
])
}
function handleImageLoad(event) {
//this function runs when the onload event completes
map = new createjs.Bitmap(img); //create a Bitmap object, then set properties
map.x = 0;
map.y = 0;
stage.addChild(map); //add the Bitmap object as a child of the stage, then update the stage
stage.update();
}
</script>
</head>
<body onload="init();">
<!==add a canvas tag==>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>
I recomend you AngularJS.
You have to call a function on HTML:
<body ng-init="initCanvas()">
<center>
<canvas id="canvas" width="602" height="447"></canvas>
</center>
</body>
In JavaScript:
var stage, image;
var initCanvas = function() {
stage = new createjs.Stage("canvas");
image = new createjs.Bitmap("img/image.png");
image.x = 0; image.y = 0; image.visible = true;
stage.addChild(image);
stage.update();
};

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>

Categories

Resources