HTML5 / JavaScript Clickevent on Image - javascript

here comes my code first..
<canvas id="myCanvas" width="640" height="480">
</canvas>
<script type="text/javascript">
// Javascript Goes Here
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var width = canvas.getAttribute('width');
var height = canvas.getAttribute('height');
//Images variables
var bgImage = new Image();
var playImage = new Image();
var shipImage = new Image();
var instructImage = new Image();
var logoImage = new Image();
//Arrays for position of Images
var buttonX = [196, 196, 150, 160];
var buttonY = [100, 140, 12, 150];
var buttonWidth = [96, 260, 182, 160];
var buttonHeight = [40, 40, 40, 40];
//Source of Images
bgImage.src = "Images/Background.png";
playImage.src = "Images/play.png";
//shipImage.src = "Images/enemy.png";
instructImage.src = "Images/instructions.png";
logoImage.src = "Images/logo.png";
//drawing Images
bgImage.onload = function () {
context.drawImage(bgImage, 0, 0);
};
playImage.onload = function () {
context.drawImage(playImage, buttonX[0], buttonY[0]);
};
instructImage.onload = function () {
context.drawImage(instructImage, buttonX[1], buttonY[1])
}
logoImage.onload = function () {
context.drawImage(logoImage, buttonX[2], buttonY[2])
}
//shipImage.onload = function () {
// context.drawImage(shipImage, buttonX[3], buttonY[3])
//}
What i want to have is a simple ClickListener on the play and instruction image. I´ve tried many options and tutorials but nothing works....
Could anybody help me please?
Thanks a lot!

You can use the following to register the handlers:
playImage.addEventListener("click", function(){
alert("Play was clicked.");
});
instructImage.addEventListener("click", function(){
alert("Instruct was clicked.");
});
Alternatively, this may also work for you:
playImage.onclick = function() { alert("Play was clicked."); };
instructImage.onclick = function () { alert("Instruct was clicked."); };
If that doesn't work for you, describe your expectations and how they aren't met by this answer.
Also, the following link to the MDN would help you with syntax questions like this in the future.

Related

Can't recognize image using OCR

I was trying to use ocrad.js to convert an image to a string, but I didn't get the result string. I was also previewing the image, the problem is only in the image recognition.
This is my code:
function pr_image(event) {
var reader = new FileReader();
reader.onload = function() {
var output = document.getElementById('output_image');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
var stringletter = OCRAD(event.target.files[0]);
document.getElementById('letter').value = stringletter;
}
and this is the browser's capture:
unchanged value
no error message in console
I've tried to change the recognition code into this one function, but i get . as the image recognition's result:
function str_img(event) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
context.drawImage(this, 0, 0);
}
var imageData = context.getImageData(0, 0, 100, 100);
var stringletter = OCRAD(imageData);
document.getElementById('letter').value = stringletter;
}
I suspect that I failed at converting the input file as image data. What should I do? Any help is appreciated!
Solved:
I've changed my code into this by Chris G and it works! Thank you
function preview_image(event)
{
var reader = new FileReader();
var output = document.getElementById('output_image');
reader.onload = function()
{
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
output.onload = function()
{
var stringletter = OCRAD(output);
document.getElementById('letter').value = stringletter;
}
}

JavaScript, Trying to get buttons to move on click

/*
var young_link = {
power: 30,
cpower: 20,
hp: 3,
image: "../images/young_link.jpg",
};
var young_zelda = {
power: 30,
cpower: 20,
hp: 3,
}
var impa = {
power: 30,
cpower: 20,
hp: 3,
}
var hey = {
power: 30,
cpower: 20,
hp: 3,
}
//$("#test").html(young_link);
console.log(young_link);*/
$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
//var test = "<img src= '../images/young_link.jpg'>";
//var young_hero = ["young_link","young_zelda","impa", "malon"];
var young_hero = ["Link", "Bongo Bongo","Gandondorf","Queen Gohma"];
var health = [100, 70, 120, 50];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<buttons>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({"data-name":young_hero[i],"data-health":health[i],"data-image":hero_image[i]});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
$(".hero_button").on("click" , function() {
var battle_ground = $("<div>");
battle_ground.addClass("hero hero_button");
battle_ground.text($(this).data("data-name"));
$("#battle").append(battle_ground);
});
});
The for loop is working and appending the buttons on the screen. But in $(".hero_button").on("click" , function() it is just putting a empty box on the page with a click. So, it is not taking the data that is attached to the button.
Sam answered your question correctly and rightly deserves the accepted answer. But I wanted to give you an insight into how you can do this in a cleaner way, without lots of arrays which must line up. Also without using jQuery at all. Below you can see a more object oriented way to do this.
You can see it in action in this jsFiddle
// Now we have an object which represents a hero. No need to duplicate loads of code.
function Hero(heroData) {
this.name = heroData.name;
this.health = heroData.health;
this.setImage = function() {
this.image = new Image();
this.image.src = heroData.imageSrc;
this.image.id = heroData.imageId;
}
this.createHeroButton = function() {
this.createButtonElement();
this.addButtonToPage();
this.attachButtonEvents();
}
this.createButtonElement = function() {
var heroButton = document.createElement('button');
heroButton.classList.add('hero,hero_button');
heroButton.setAttribute('name', this.name);
heroButton.setAttribute('health', this.health);
heroButton.appendChild(this.image);
this.button = heroButton;
}
this.attachButtonEvents = function() {
this.button.addEventListener('click', this.addButtonToPage.bind(this));
}
this.addButtonToPage = function() {
var container = document.getElementById('container');
container.appendChild(this.button);
}
this.takeDamage = function(damageValue) {
this.health -= damageValue;
this.button.setAttribute('health', this.health);
}
this.setImage();
}
// So here we create a Hero instance, in this case Link, we can use now describe links attributes, image, name, health...
var link = new Hero({
name: 'Link',
health: 100,
imageSrc: 'http://orig12.deviantart.net/8bb7/f/2011/276/4/e/four_swords_link_avatar_by_the_missinglink-d4bq8qn.png',
imageId: 'link-image'
});
var mario = new Hero({
name: 'Mario',
health: 100,
imageSrc: 'http://rs568.pbsrc.com/albums/ss123/stvan000/thumb-super-mario-bros-8bit-Mario.jpg~c200',
imageId: 'mario-image'
});
// Now we can easily make a button and add it to the page
link.createHeroButton();
mario.createHeroButton();
// Lets try decreasing the health on mario
mario.takeDamage(10);
// Because we have an object reference which handles all of our heros state we can decrease his health and update the buttons data without much trouble.
A couple of changes to get the data set and read correctly:
make button tags instead of buttons
use .attr() instead of .data() to get the attributes
See comments inline in the code below.
Also, instead of adding an attribute for the Image object of each item (which will add an attribute like data-image="[Object object]") just add an integer corresponding to the iterator index and use that to reference into the hero_image array when you need to get the corresponding image.
Additionally, you can use Array.forEach() to iterate over the items in the heroes array with a callback function. That way you don't have to worry about updating the iterator variable (i in this case) and indexing into the array. You should take a look at this functional programming guide which has some good exercises.
$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_heroes = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
young_heroes.forEach(function(young_hero,i) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero,
"data-health": health[i],
//instead of adding an attribute for the image object, just add an index
"data-index": i
});
hero_btns.text(young_hero);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
});
$(".hero_button").on("click", function() {
var battle_ground = $("<div>");
battle_ground.addClass("hero hero_button");
//use .attr() here instead of .data()
battle_ground.text($(this).attr("data-name"));
/** My additions -
* I am not sure exactly how this should be done
* so adjust accordingly
**/
//additionally, you can add attributes to the new battle_ground item
battle_ground.attr('data-health',$(this).attr("data-health"));
battle_ground.append(hero_image[$(this).attr("data-index")]);
battle_ground.append($(this).attr("data-health"));
/** End my additions **/
$("#battle").append(battle_ground);
});
});
#battle div {
border: 1px solid #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons"></div>
Battle ground:
<div id="battle"></div>

tick method in javascript for canvas

I'm trying to make a tick method for this code.
When I try to put a while loop or time interval it just goes blank.
I want the tick method to call this function without the canvas going blank.
How would i make that tick method
function setup(){
var canvas = document.getElementById('my_canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var gun = new Image();
var badguy = new Image();
var wall1 = 200;
var ground = new Image();
var back = new Image();
var back2 = new Image();
var back3 = new Image();
var wall = new Image();
var wall2 = new Image();
back.onload = function() {
ctx.drawImage(back, 0, 0, 800, 300);
};
back2.onload = function() {
ctx.drawImage(back2, mountainplace, 0, mtnsize1, 300);
};
back3.onload = function() {
ctx.drawImage(back3, mountainplace2, 0, mtnsize2, 300);
};
ground.onload = function() {
ctx.drawImage(ground, groundplace, 300, 1980, 200);
};
wall.onload = function() {
ctx.drawImage(wall, place2, 250, size2, 100);
};
wall2.onload = function() {
ctx.drawImage(wall2, place, 250, size, 100);
};
badguy.onload = function() {
ctx.drawImage(badguy, badguyplace, 250, 100, 100);
};
gun.onload = function() {
ctx.drawImage(gun, 0, 100, 400, 400);
};
back2.src = "moutain1.png";
back3.src = "moutain2.png";
back.src = "backing.png";
ground.src = "ground1.jpg";
wall.src = "wall.png";
wall2.src = "wall2.png";
badguy.src = "santa2.png";
gun.src = "gun1.png";
};
You need to clarify the question because I'm not sure what exactly you are trying to achieve.
I assume you put some code at the end of your setup() function that performs some operations on the images. But before you can do it you need to wait for the images to load.
BTW: another problem with your code is that the images will be drawn on the canvas in the order in which they load, which may be unpredictable. You probably want to avoid this too.
A solution to your problem (or at least to what I think your problem is) is to first start loading the images and then only perform further operations after they have all been loaded.
You can use the following code to do this:
function makeAllLoadedHandler(image_files_count, on_all_loaded) {
return function() {
--image_files_count;
if (image_files_count == 0) {
// All images loaded, call the function.
on_all_loaded();
}
}
}
function loadAllImages(image_files, on_all_loaded) {
var images = {};
var callback = makeAllLoadedHandler(image_files.length, function() { on_all_loaded(images); } );
for (var i = 0; i < image_files.length; ++i) {
var image = new Image;
image.src = image_files[i];
image.onload = callback;
images[image_files[i]] = image;
}
}
The loadAllImages() function takes an array of image file names and a function to call when all the images have been loaded.
You can use it like this in your code:
function setup() {
var image_files = [
"mountain1.png",
"mountain2.png",
"backing.png",
"ground1.jpg",
"wall.png",
"wall2.png",
"santa2.png",
"gun1.png" ];
loadAllImages(image_files, onAllImagesLoaded);
}
function onAllImagesLoaded(images) {
// Draw your images and perform all the other tasks on them.
// The 'images' object stores each of the Image object under a key that is
// its file name.
ctx.drawImage(images['backing.png'], 0, 0, 800, 300);
// ...
// Do other stuff with the images.
}
You just call the setup() function like you used to and then the onAllImagesLoaded function will be called some time later when all the images are available. You continue your processing in there.
I hope this helps. Although it's possible that your problem is completely different ;)

Getting width of image (by URL) outside function w/ JavaScript

I'm trying to get the width of two images based on their URLs (so, actual image size). I'm able to do that in such a way so as to pop up an alert based on the results, but anything outside of the actual function results in an undefined value for the widths of the two images.
var w1 = "";
var w2 = "";
var img1 = new Image();
img1.onload = function() { w1 = this.width;};
img1.src = "URL1";
var img2 = new Image();
img2.onload = function() { w2 = this.width;};
img2.src = "URL2";
alert (w1 + " and " + w2);
How do I use w1 and w2 outside of the functions that set them to this.width?
Ideally I'd like to compare them and later on use the larger one. But I can't even get them to show with their correct values in the alert (above).
Thanks in advance!
Adendum:
var img1 = new Image();
var img2 = new Image();
var one, two;
img1.src = "img1.jpg";
img2.src = "img2.jpg";
img1.onload = function() {img2.onload = function() {compareWidth(img1.width, img2.width);}}
var finalchoice;
var compareWidth = function (width1 ,width2){
if(width1 > width2){
finalchoice = img1.src;
alert(finalchoice);
return finalchoice;
}
else{
finalchoice = img2.src;
alert(finalchoice);
return finalchoice;
}
}
Idea being then to use final choice later in the .js file.
The alert (w1 + " and " + w2);
statment is executed before the image is loaded that's why the result is displaying undefined.
To compare the width of two images you can use this code.
<!DOCTYPE html>
<html>
<head>
<body>
</body>
<script>
var img1 = new Image();
img1.src = "w3javascript.gif";
img1.onload = function() {
document.body.appendChild(img1); //this is optional you can remove it
compareWidth(this.width);
}
var img2 = new Image();
img2.src = "author.jpg";
img2.onload = function() {
document.body.appendChild(img2); //this is optional you can remove it
compareWidth(this.width);
}
var w1;
var compareWidth = function (width){
//here you can do operation with width and height
if(typeof w1 == 'undefined'){
w1 = width;
}else{
if(w1 < width){
alert('do one thing');
}else{
alert('do other thing');
}
}
}
</script>
</html>
i would recommend using jQuery...
Just load jQuery ... > like <script src="{jquery-lib-path}"></script>
and do something like
var imgWidth = img.width():

Issue with new Image() in Javascript

The code:
function CreateAndAnimateEnemyImg() {
var enemy = new Image();
enemy.src = 'enemy.jpg';
enemy.class = 'Enemy';
enemy.width = '30px';
enemy.height = '30px';
document.body.appendChild(enemy);
enemy.onload = function () {
alert('2. Image has fully loaded.');
$('.Enemy').animate({ 'right': '+=20px' });
}
}
$("#Start").click(function () {
CreateAndAnimateEnemyImg();
});
The weird behavior is that the alert is raised but no image is shown, nor the animation is working. Any help please?
Change your code:
enemy.className = 'Enemy';
enemy.width = '30'; // no px needed
enemy.height = '30';
http://jsfiddle.net/UqcqN/
You have two mistakes: if you set width property you don't have to provide units. And you should set className property instead of class.
It is also recommended to set src after onload handler.
You have to enemy.src = 'enemy.jpg'; AFTER you define: enemy.onload.
i think no need for giving string kind of 'px';
rtefer this http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_height
here is the complete demo Fiddle
function CreateAndAnimateEnemyImg() {
var enemy = new Image();
enemy.src = 'http://media.steampowered.com/apps/440/icons/icon_dueling_large.14fd9f2da0f24b2dfaac37d1600c821ddb6d3456.png';
enemy.class = 'Enemy';
enemy.width = '130';
enemy.height = '130';
document.body.appendChild(enemy);
enemy.onload = function () {
alert('2. Image has fully loaded.');
$('.Enemy').html(enemy);
console.log(enemy);
$('.Enemy').animate({ 'right': '+=20px' });
}
}
$("#Start").click(function () {
CreateAndAnimateEnemyImg();
});

Categories

Resources