Onclick on image that is created in a javascript canvas - javascript

Hiho,
I prepared a snippet.
As in my example I'm using the drawImage function to draw images to a game, because I don't want to include them all in HTML ... However, my problem is, I can't find any possibility to give those "own created" images an onclick function. I thought the object "Image" (var someImage = new Image();) was comparable to the HTML <img> or <input type="image">, but no matter how hard I try, I can't make it.
Can anyone help me?

You've given the click event to the canvas context and not the canvas, change it to:
myCanvas.onclick = function()
As for making the individual images clickable (if you draw more than one), you can always keep an array of the clickable areas and the links they should go to that correspond to the images, then add a loop to the canvas click to check that the mouse co-ords match up to on of the areas in the array.
Example : JSFiddle Code

Related

Paper js - Raster onClick event attached only to position Point

I am using PaperJS and I need to use an existing set of icons that I can receive as a base64 string (that's a given I can't change). I have no problem rendering the rasters.
However when I set them a position like so:
const myRaster = new Raster(<someBase64>);
myRaster.position = new Point(receivedX, recievdY);
myRaster.onClick = () => console.log('raster click');
The onClick event would only work if I click exactly on [x,y] point assigned to the position property.
The X and Y are received form a data base and are in accordance to other visible elements.
I played around in the PaeprJS website, and without using a new Point position the onClick works all around the image.
My solution for now is creating an invisible polygon (new Path.RegularPolygon) and to attach to onClick event to it and it works.
However, there's must be a simpler solution and would love to understand what I am missing here.
Thanks!
Apparently, the SVG was partially created programmaticly and had a lot of whitespace around it.
Testing with base64 encoded SVGs from various different sources worked as expected

HTML/CSS Hover over image for close up image/test/hyperlink

I'm building a resource website for the facility I work and need help with a script.
I have an image of multiple medications that i'd like to hover to display more info. The following link is an example i found online.
image link
I'd like to be able to hover each medication to have a window pop up next to it with a close up image, the name of the drug, and a hyper link to an external site. What would the easiest way to achieve this.
Thanks so much!
Use an image map and some javascript mouse event action. The main image is an image map with rectangular/circular 'area' regions. Infos are put into 'div' blocks that are made visible/invisible with style property 'display' set to 'block' or 'none'. The init() function makes all 'div' blocks invisible at start.
HTML:
<img src="XYZ" alt="medications" usemap="#medsMap">
<map name="medsMap">
<area shape="rect" coords="x,y,w,h" onmouseover="showInfo('med1')" onmouseout="hideInfo('med1')" >
<area shape="circle" coords="x,y,r" onmouseover="showInfo('med2')" onmouseout="hideInfo('med2')" >
</map>
<div class="medInfo" id="med1">
// All your html about medication 1
</div>
<div class="medInfo" id="med2">
// All your html about medication 2
</div>
Javascript:
window.onload = init;
function init(){
var infos = document.getElementsByClassName('medInfo');
for (var i=0, i<infos.length, i++){
infos[i].style.display = 'none';
}
}
function showInfo(divId){
document.getElementById('med1').style.display = 'block'
}
function hideInfo(divId){
document.getElementById('med1').style.display = 'none'
}
easiest may not be the best in the case... however a simple solution would be something with abosolute positioned divs inside a relative positioned container div with the image set to the background. you could assign a click handler to each one to grab the data from an object and populate the target... the data might look something like this
var myItems = {
item1: {
img: 'http://www.photo-dictionary.com/photofiles/list/6666/8841blue_pill.jpg',
headline: 'the blue pill',
body: 'this pill is blue and comes in a purple box'
},
item2: {
img: 'http://www.photo-dictionary.com/photofiles/list/6679/8857red_pill.jpg',
headline: 'the red pill',
body: 'this pill is red and comes in a red box'
}
};
here is an example of that concept in a fiddle
http://jsfiddle.net/pixelchemist/3fL8P/
It's difficult to give a "good" answer without seeing what the actual data is you wish to display. However from what you have provided the most accessible method would be to use an HTML image map.
Here are the MDN docs for the separate HTML elements you will need to use:
Map link
Area link
Essentially you define rectangles, circles or polygons (using coordinates) which "overlay" the associated image. Each area can have an alt attribute which screen readers will be able to use for those viewing your site with visual impairments. The href attribute will provide you with the link to the external site.
Now there are several offline tools that can help you create image maps, here is an online one ...I am not necessarily recommending it over others, however it will provide you with an idea of how they work.
Once you have the accessible version in place, you can use JavaScript to provide extra functionality on top of that. How you wish to do that is really up to you, and again would be defined by the exact content you wish to display, and there are several pre made scripts out there for the purpose, however if you were simply wanting to display the alt/href in a basic tooltip then it wouldn't require more than a few lines of bespoke HTML/JavaScript.
Again, without recommending them, here are a couple of common solutions:
solution 1 and solution 2
Even if this is not exactly what you are looking for, it should provide you with some help at deciding your final solution.

Looking for advice on what approach to take for multiple image swaps

I'm working on designing an interactive university campus map and need some direction with what I am looking to do.
Link to page: http://www.torontoclassfind.com/startpage.html
I want to be able to click on the links in the top menu (only one link is active so far and it loads and Ajax page in lower left div) and have it swap the building image with a different image to show that it's been selected.
I could do that with the following:
$("#buildinglink1").click(function () {
$("#buildingimg1").attr("src","highlightedimage.gif")
})
Problem is I need to change back the image to it's default image once another menu link is clicked and a new building is selected.
The building images are located at www.torontoclassdfind.com/building/ and the highlighted images are located at www.torontoclassdfind.com/buildingc/ and the names for the buildings are the same in both locations.
I am thinking of using JQuery's .replace element to do this (ex: jquery remove part of url) which would remove or add the 'c' to the url, but I'm kind of lost from here.
Any tips? I think I need to make a function that would indicated a link is selected and somehow merge it with the .replace element.
Just a note: .replace is a JavaScript string (and others) method, not a jQuery method.
I think you're asking to do something like this:
$(".any-building").click(function () {
//replace all building sources with the unhighlighted version
$(".any-building").attr('src', function () {
return $(this).attr('src').replace('buildingc', 'building');
});
//replace clicked image with highlighted one
$(this).attr('src', $(this).attr('src').replace('building', 'buildingc'));
});
A possible downside is that with a lot of images this swap may take a long time or cause some flicker. If that's the case, then you may want to add a class .active to the highlighted image or something like that and only do the swap for that image and the newly clicked one.
A common learning mistake in jQuery is to focus on ID's for all types of selectors. They work great for very small number of elements however become very unwieldy fast for large groups of elements that can easily be managed by simpler code methods.
You want to be able to write far more universal code where one handler would cover all of your links that share the same functionality in the page .
Example:
var $mainImage=$('#mainImage')
var $buildingLinks=$('.buildingliststyle a').click(function(){
/* "this" is the link clicked*/
/* get index of this link in the whole collection of links*/
var index=$buildingLinks.index(this);
/* perhaps all the image urls are stored in an array*/
var imgUrl= imagesArray( index);
/* perhaps the image urls are stored in data attribute of link( easy to manage when link created server side)*/
var imgUrl=$(this).data('image');
/* store the current image on display (not clear how page is supposed to work)*/
var currImage=$mainImage.attr('src');
$mainImage.data('lastImage', currImage);/* can use this to reset in other parts of code*/
/* nw update main image*/
$mainImage.attr('src', imgUrl);
/* load ajax content for this link*/
$('#ajaxContainer').load( $(this).attr('href') );
/* avoid browser following link*/
return false;
});
/* button to reset main image from data we already stored*/
$('#imageResetButton').click(function(){
$mainImage.attr('src', $mainImage.data('lastImage') );
})
Can see that by working with groups of elements in one handler can do a lot with very little code and not needing to focus on ID
Code above mentions potentially storing image url in data attribute such as:
Building name

images created dynamically do not appear on screen! -> Javascript

I'm trying to do something simple to practice my Javascript (which I learned some recently) and I'm trying to do a game on it (pacman to be precise).
I am trying to build that game board on the browser by creating images dynamically. I've done an array like this:
var images= new Array(25);
for(i=0;i<25;i++)
images[i]= new Array(25);
And, for the game board I used a matrix done with 0 and 1's with 25x25 size (not going to post it here cause is too big and would make my text hard to read) called board.
For the images that I am using right now I have something like this:
var image_empty = new Image();
image_empty.src="Images/empty.jpg";
var image_wall = new Image();
image_wall.src="Images/wall.jpg";
For the initialization function I have something like this:
function drawField()
{
for(i=0;i<board.length;i++)
{
for(j=0;j<board[i].length;j++)
{
if(board[i][j] == 0)
draw(i,j,image_empty);
else if(board[i][j] == 1)
draw(i,j,image_wall);
}
}
}
And for drawing the images themselves I am using this:
function draw(x,y,img)
{
images[x][y] = new Image(22,22);
images[x][y].src = img.src;
images[x][y].style.position = 'absolute';
images[x][y].style.left = 40+x*22;
images[x][y].style.top = 40+y*22;
}
Every time I run this code nothing appears on the screen. I've tried several times use a load of things but nothing happens. I am saving the pictures (at least I think I am) and still nothing.
Can someone give me some pointers of what could be wrong?
PS: Some people pointed me out using the appendChild method would solve the problem, still, since pacman will be moving around I can't use it to store my images (and I was planning to use the draw function to draw anything).
And btw nor Web Developer plugin or firebug point out errors (the code is correct from their perspective).
Creating an Image in the method you describe doesn't actually display the image. Even putting attributes and styling to make it appear a certain way doesn't add it to the DOM. The advice about append child is correct. For example, if you had:
<div id="main"></div>
and you called
document.getElementById("main").appendChild(images[x][y]);
this would insert the image inside the div. You could do this repeatedly to generate the equivalent of...
<div id="main">
<img src... />
<img src... />
...and so on
</div>
Then, your CSS styling and positioning would work.
There's nothing wrong with your script, but Firebug does display a rendered version of the DOM. As you run the script, you will actually see the HTML tab of Firebug changing with the images you've added to the page.
Also, keep in mind that the DOM must complete loading before you are able to run this. You can accomplish this by doing a simple:
<body onload="drawImages()">
UPDATE: Once you've actually added the 25x25 images, the array still references the elements - they're just now part of the DOM. So, you can change their source via:
images[x][y].src = "newImage.jpg";
If you, for some reason, wanted to remove an image from the board, leaving a gap, you can remove it from the DOM
document.getElementById("main").removeChild(images[x][y]);
or just hide it via CSS.

Updating target href problem

I'm working on a little image gallery, where you'd roll over a small thumbnail, the larger image would display over it. Clicking on the image would load a full size version in an overlay.
http://shopcoobie.server303.com/shop/
The issue is with the larger image, the rollovers are working fine, but the script I have updates the href which points to the full size image only seems to work the first time I click the image.
$$('.thumbs img').each(function(s) {
$(s).observe('mouseover', function(e) {
var el = e.target;
var thumb = $(el).src;
var large = $(el).alt;
$(el).up(3).down(1).href = large;
$(el).up(3).down(2).src = thumb;
console.log((el).up(3).down(1).href);
console.log(thumb);
});
});
The console outputs the proper image reference, so it seems this should work (and partially does), Im just not sure why it only works once.
Thanks
Rich
I think the lightview plugin builds up its list of images first, then you change the src dynamically, and it doesn't update. So try adding a call to Lightview.updateViews(); at the end of the mouseover handler above.
From Lightview:
Lightview.updateViews(): Force a reset of all Lightview
elements on the page. Most of the time
you won't need to do this since
Lightview will pick up on newly
inserted elements automatically. After
updating existing elements it might be
required to call this function.
So yours is a case where it doesn't automatically pick up the change.

Categories