Show base64 image next to canvas with charts.js - javascript

I'm using charts.js which has an option to add an attribute containing a base64 image of the canvas, like this:
animation: {
onComplete: function(animation){
document.querySelector('#myChart').setAttribute('href', this.toBase64Image());
}
},
Here is the full working fiddle: https://jsfiddle.net/0on3f7t7/
When you inspect the canvas you can see a href attribute containing the image, so that works. But instead I need to display the image below the canvas. So, yes, there will be two charts on the screen, the canvas version and the image version.
I can't find an answer to this question anyway, and the documentation doesn't give any clues.

You need to add an <img> element to your page, and then set the src attribute of the <img> element to the output of this.toBase64Image()
See the following fiddle:
https://jsfiddle.net/wveepa7c/
onComplete: function(animation){
// #myImage is an img element
document.querySelector('#myImage').setAttribute('src', this.toBase64Image());
}

onComplete is called at least two times at jsfiddle. You can define a variable which is undefined, at onComplete check if variable is defined to prevent <img> being appended to document twice, if variable is not defined, create <img> element, use .insertAdjacentHTML() chained to ctx with first parameter "afterend" and second parameter .outerHTML of <img> element
var img;
animation: {
onComplete: function(animation) {
if (!img) {
ctx.setAttribute('href', this.toBase64Image());
img = new Image;
img.src = ctx.getAttribute('href');
ctx.insertAdjacentHTML("afterend", img.outerHTML)
}
}
}
https://jsfiddle.net/0on3f7t7/2/

Related

How to make a photo appear when clicking on another photo? Javascript, DOM

I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.

Significance of two different img's in the given code?

It is a link to w3schools Website for a JS tutorial
In the above program I found that there are two src's of image in the ( if loop ) i.e. img src="pic_bulboff.gif" and img src= "pic_bulbon.gif". Why is there a need for two img src's?
What is the use of "match" in this program?
The src attribute is the URL for the image - it's what gets displayed. That's not a loop, it's an if statement - a branching or conditional statement - and only one of the branches will be taken each time the function is called. It is a toggle - when you click the light, it switches the src attribute to the one not currently selected.
match is a function on a string that takes a regular expression. If you are just getting started programming, that's a deep rabbit hole to go down, but basically it's checking whether the current src attribute value contains that text or not.
It is checking if the image is the bulbon image, if it is then it changes it to the bulboff image and vice-versa.
To answer your question let's look at the whole code:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
</body>
</html>
As the problem states, the whole point is to change<img> src attribute upon clicking the <img> tag.
That implies that if the light is on, meaning if the src attribute of the <img> tag contains the word off, we want to change the src to be src="pic_bulbon.gif". This should work like a normal light bulb, on and off. Each image represents a bulb that is off or a bulb that is on.
Match is the key to the solution. What match does is that it will look at a string and find a word within that string, if such word exists then it will return true.
Using match on the string from the src attribute will help us to find a the word on or off*. So considering what the src attribute contains, pic_bulbon**.gif or pic_bulboff.gif, we will match like so in JavaScript:
stringName.match(someOtherString), which translates to image.src.match("bulbon") or image.src.match("bulboff") conversely.
After this we can set the src attribute to on or off via the if/else statement:
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
If you still have any questions please ask in the comments below.
This is what the code is doing: Working Example with logging
function changeImage() {
// grab the element (in this case an img tag) using the id 'myImage'
var image = document.getElementById('myImage');
// check to see if the source of the image contains the word 'bulbon'
// match return an array of matches
if (image.src.match("bulbon")) {
// if there is a match for bulbon change the image src to pic_bulboff.gif
image.src = "pic_bulboff.gif";
} else {
// if not change it to pic_bulbon.gif
image.src = "pic_bulbon.gif";
}
}
// on match:
var s = 'aaaabulbonaaa';
var matchResult = s.match('bulbon');
// match return an array of matches
console.log(matchResult); // ["bulbon"]

Jquery replaceWith keep onclick

How can I keep onclick="" value with JQuery replaceWith ? I'm making a assets system that preload every image and put it on a Javascript image() object, and using a special data attribute for img urls
<img data-assets="images/test.png" onclick="alert('test')">
turn into : (using jquery replaceWith)
<img src="assets/images/test.png">
What I want:
<img src="assets/images/test.png" onclick="alert('test')">
My code:
$("[data-assets]").each(function() {
$(this).replaceWith(Game.Preloading.Assets.Images[$(this).data('assets')]);
});
How can I fix that ? Thanks
While iterating over each [data-assets] element, you could set the corresponding onclick attribute before replacing the element:
$("[data-assets]").each(function() {
var $newImg = $(Game.Preloading.Assets.Images[$(this).data('assets')]);
$newImg.attr('onclick', $(this).attr('onclick'));
$(this).replaceWith($newImg);
});
However, it would be better to just add a src attribute on the existing element rather than replacing it:
$("[data-assets]").each(function() {
this.src = $(Game.Preloading.Assets.Images[$(this).data('assets')]).attr('src');
});
Ideally, you should be using unobtrusive JavaScript and avoiding the inline JavaScript event listeners, but both of the above snippets should work.
I think you would be better off to simple query for your attribute, then use the each method to update the SRC attribute on each matched element.
Im on my phone so a more detailed answer is difficult...
But here goes
$("[data-assets]").each(function(){ $(this).attr("src", Game.Preloading.Assets.Images[$(this).data('assets')]); });

Removing image src attribute

Removing the src attribute on an image tag doesn't seem to redraw the view on iOS(7) or Android (KitKat). Neither does changing the attribute to a blank value. Desktop browsers work as expected.
This DOES remove the attribute but the view doesn't reflect the change:
$('#imgPreview').removeAttr('src');
This DOES change the attribute but the view doesn't reflect the change:
$('#imgPreview').attr('src','');
If the attribute is changed to a valid image path, the view DOES update:
$('#imgPreview').attr('src','http://some/image/path.jpg');
I have a simple test case HERE that shows the issue.
Is there a way that I can force a redraw after changing the src attribute to a blank value or removing the src attribute altogether?
You could force element redraw using this kind of snippet:
$.fn.redraw = function(){
return this.hide().show(0);
};
Or maybe better:
$.fn.redraw = function(){
return this.each(function(){
var zIndex = $(this).css('z-index');
$(this).css('z-index',-1).css('z-index',zIndex);
});
};
Then use it as e.g:
$('#imgPreview').removeAttr('src').redraw();

Thumbnail gallery that loads image description and full size on same page on click

I want to create something like this.
Where do I get started with the javascript? Also, is it possible to customize something like this with the Nextgen Gallery plugin or another Wordpress plugin?
You will need two things:
A data Object that maps the thumbnail src value (or any other identifer) to the required URL and description Strings.
Some Event handler for the thumbnails that get the respective entries in the data Object and set the highlight img Node's src attribute as well as the description text.
So, let's say this is your data Object:
var data = {
<src>: {
"url": <url for the large image> ,
"text": <description for the large image>
} ,
<another src>: {
//..
}
}
Now, you just have to get the src of the thumbnail img Node that raised the Event and get its respective entry in the data Object,
var img = /* the reference to the img Node that raised the event */ ;
var src = img.getAttribute("src") ;
var entry = data[src] ;
var url = entry.url , text = url.text ;
; then you simply have to change the src attribute of the large img Node and the text content of the Node containing the description.
You could also do the same thing using the id attribute.
HTH

Categories