How to generate a html2canvas images with a hidden source (html) div - javascript

I am working in a project where I need to generate a profile picture of any member and its reviews, and some data, I started working with GDI, but it was so hard to understand, so I searched for other options and found Html2Canvas that works with javascript/jquery, everything is fine, the only thing I couldn't handle, and would like to know if there is a way to hide the source html div without breaking the result image.
Ex:
This is how is it now
This is how it should look
So, when I apply display:none on the css of the source div, the image result is like this:
And finally here is the code that I have so far
var div_to_hide = $("#mydiv:hidden");
$(function() {
$('span.stars').stars();
});
html2canvas([document.getElementById('mydiv')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
$.fn.stars = function() {
return $(this).each(function() {
var val = parseFloat($(this).html());
val = Math.round(val * 4) / 4;
var size = Math.max(0, (Math.min(5, val))) * 16;
var $span = $('<span />').width(size);
$(this).html($span);
});
}
https://jsfiddle.net/ricardojriosr/6ap9Lx1f/8/
Now the question is how do I made this work showing only the image and not the HTML source. Thanks in advace.

Instead of trying to hide it before, hide (or remove) it after the canvas is rendered.
I'm not sure why var div_to_hide equals $("#mydiv:hidden"); but if you change it to var div_to_hide = $("#mydiv"); then, on line 12, after appending the image, you can run div_to_hide.hide();
And to avoid a flash of the HTML content, you can use some CSS trickery to cover up the original HTML. I made an example here, but you can adjust to fit whatever your actual needs are. https://jsfiddle.net/m5zq2kzn/

I had the same issue.
The solution that worked for me is a css trickery to position the div that I want to hide offscreen:
.offscreen {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;
}
Then use it like this:
html2canvas(document.getElementById("ticket_template"))
.then((canvas) => {
let imgData = canvas.toDataURL('image/png');
});

Related

Assign array of image elements to DOM ids

I have an array of URIs that represent .png elements, e.g., "./img/diamond-red-solid-1.png".
I want to assign each element of the array "gameDeck[0], gameDeck[1], etc. to div ids in HTML. Do I need to identify the elements as = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
The way I'm understanding your question is that you would like to target the divs in your HTML with ids of card1, card2, card3... card12 etc.
You would like to insert an img tag into each of these divs with the src being the URIs of the gameDeck array.
The following code achieves this. I've tested it and it works fine. Hope it helps :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
Here is a way that you can either insert images as background images, or as <img /> elements into the divs you are referring to:
<div id="card0" style="width: 100px; height: 100px;"></div>
<div id="card1" style="width: 100px; height: 100px;"></div>
let loadedImage = [];
function preloadImages(urls, allImagesLoadedCallback) {
let loadedCounter = 0;
let toBeLoadedNumber = urls.length;
urls.forEach(function(url) {
preloadImage(url, function() {
loadedCounter++;
console.log(`Number of loaded images: ${loadedCounter}`);
if (loadedCounter == toBeLoadedNumber) {
allImagesLoadedCallback();
}
});
});
function preloadImage(url, anImageLoadedCallback) {
img = new Image();
img.src = url;
img.onload = anImageLoadedCallback;
loadedImage.push(img);
}
}
function gameBoardCards() {
for (let i = 0; i < loadedImage.length; i++) {
document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`;
// document.getElementById(`card${i}`).appendChild(loadedImage[i]);
}
}
preloadImages([
`https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/Color_icon_green.svg/2000px-Color_icon_green.svg.png`, `https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/225px-Solid_blue.svg.png`
], function() {
console.log(`all images were loaded`);
gameBoardCards();
// continue your code
});
It may seem like a bit much for what you are trying to accomplish, but I threw in a proper image-loading handler there. The preloadImages function will handle the loading of images, that way they are properly preloaded, and can render to the DOM. Often times, we try to use images before they are properly loaded, resulting in them sometimes not being displayed, despite no errors are being thrown.
The rest of the code is straight forward, in the for loop, it loops through the existing divs and you can either use the current active line document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`; to use the loadedImage[i] image src to load that as the divs's background image. Or you can use the commented-out line directly below that document.getElementById(`card${i}`).appendChild(loadedImage[i]); to insert an <img /> element into that div. Just use either one that works for you.
You can see the code in action in this JS Fiddle demo.
Hope this helps :)

Javascript: Display clickable images at the end of each paragraph

$(document).ready(function(){
function createPopup(event){
$('<div class="popup"><img src="mysrc.jpg" img style="opacity=0.5; width:50px; height:50px;"></img></div>').appendTo('body');
positionPopup(event);
};
function positionPopup(event){
var tPosX = 950;
var tPosY = event.clientY+25;
$('div.popup').css({'position': 'absolute', 'top': tPosY, 'left':tPosX});
$('#test').attr('ydown', parseInt(tPosY)+ parseInt(add));
};
var elements = document.getElementsByTagName('cposs');
for(var i = 0; i < elements.length; i++){
var imagetest = document.createElement("img");
imagetest.src = "mysrc.jpg";
elements[i].onmouseover = function(){
this.style.background = 'Green';
createPopup(event);
}
elements[i].onmouseout = function(){
this.style.background = '';
}
var ycoor= $('#test').attr('ydown');
$( "#test" ).append( "<a href=http://www.google.com><img src='mysrc.jpg'</img></a>" );
}
});
</script>
<div id="test" ydown="<?php echo $ydown; ?>" xdown="<?php echo $xdown; ?>">
There is then multiple paragraphs with <cposs></cposs> tags and this allows the text to be highlighted when the mouse is hovered over and creates a popup image to the right of the paragraph. I also have for each counted <cposs></cposs> an image that is displayed in the test div.
There is a couple things I was hoping I would be able to accomplish:
On page load, I would like an image to be displayed at the end of each <cposs></cposs> text. Instead of fixed coordinates.
I would like these images to execute a function when clicked on.(Tried adding the "onclick" attribute but said the function was not defined)
Eventually, I would like the clickable images to cause the text between the cposs tags to highlight. Similar to what I have now, but instead of mouse over, its a click event.
EDIT:
I have tried to add an onclick attribute to the appended image but once the image is clicked, says the function is not defined.
I am unsure on how to get the coordinates of the cposs tags. I am confused on if I am able to use offset and or position function in javascript. I have attempted to use both and have not succeeded.
I guess all I really need to know if how to get the end coordinates of the cposs tags and how to give each displayed image a clickable function
I am a big fan of jsfiddle!
Any sort of help is greatly appreciated!
Thanks in advance.
Here's a jsFiddle example: https://jsfiddle.net/sn625r3z/14/
To make freshly added elements clickable you should be using jQuery's ".on" function and pass an event to it. Something like this:
$('img.new-image').on('click', function(){
$(this).parent().css({background: 'green'});
});
In the jsFiddle example I positioned images with CSS. But if you want to get the coordinates to position the image at the end of the block I would do it like this:
$('cposs').each(function(){
var el = $(this);
var width = el.width();
var height = el.height();
var newElement = $('<img class="new-image" src="'+imagetest.src+'" />');
el.append(newElement);
newElement.css({top: height+"px", left: width+"px"});
});
Hope this helps.

Initializing a plugin AFTER a foreach loop

So I'm trying to implement stellar.js but it must be initialized after an each loop is finished. The loop must add data attributes to the images that are going to be made parallax by the plugin.
The images are in a list:
<ul>
<li class="item">
<div class="item-image" data-stellar-background-ratio="0.7" data-image="http://picjumbo.picjumbocom.netdna-cdn.com/wp-content/uploads/IMG_7706-1300x866.jpg"></div>
</li>
...
</ul>
I must add data-stellar-vertical-offset attribute to each of them that will offset the image by half of its height, so it can be vertically centered initially.
Here is the JS:
/* Inserting the background image */
$('.item-image').each(function () {
var $this = $(this);
$this.css('background-image', 'url(' + $this.data('image') + ')');
})
/* Creating loop that will run as many times as items are in there */
var items = $('.item-image').length;
var currentItem = 0;
$('.item-image').each(function () {
var $this = $(this);
/* Taking the origin height, halving it and putting it as offset so the image can be vertically aligned */
var img = new Image();
img.src = $(this).data('image');
img.onload = function () {
var H2 = this.height;
$this.attr('data-stellar-vertical-offset', -(H2 / 2));
}
currentItem++;
/* Initializing the plugin after every item is looped */
if (currentItem >= items) {
$.stellar();
}
})
However when the plugin is initialized it isn't using the data attribute. If it's put in a timeout like this:
if (currentItem >= items) {
setTimeout(function () {
$.stellar();
}, 10)
}
.. it works but it seems to me like an ugly hack. Is there a better way for this to be done?
Here is a jsfiddle: http://jsfiddle.net/9f2tc/1/
I believe what you want is to initialize stellar once after all the images have been downloaded. The simplest approach is to check each time in the onload handler:
img.onload = function () {
var H2 = this.height;
$this.attr('data-stellar-vertical-offset', -(H2 / 2))
if (++currentItem === items) {
$.stellar();
}
}
jsfiddle: http://jsfiddle.net/X6e9n/2/
However, there are issues with the onload event not firing for images in certain cases. See the caveats section on the jQuery page: http://api.jquery.com/load-event/ The problems listed apply to the load event itself not just jQuery's .load() See Javascript callback for knowing when an image is loaded for solutions. The first answer notes the handler should be attached before the src attribute is set, which you don't do here, but it doesn't seem to be a problem for me in this case.

Dynamically add pictures using javascript.

I've been working on a flowchart type program that changes various parts of the html each time a new question is posed (this question is represented by the 'state' variable below), things like Title, description and images.
Currently, my HTML for the images is:
<a id="imageLink" target="_blank" href=""><img class= 'right' id= 'imageBox' style ='max-height:50%;' src='' /></a>
<h3 id ='imageBoxText' ></h3>
and the image link and the legend for the image are found in imageArray which looks something like this:
imageArray = {'questionOne': ['www.link to image.com,'Legend for image']}
In this case 'questionOne' would be 'state'.
So far, I can load a single image asynchronously using:
document.getElementById("imageBox").src = "http://www.ktcagency.com/img/loader.gif"; // load spinner
var img = new Image(); // load image asynchronously
var newsrc = imageArray[state][0];
img.onload = function () { // onload handler
document.getElementById("imageBox").src = newsrc;
};
img.src = newsrc;
I also add the description and link to the image while I'm at it:
document.getElementById("imageLink").setAttribute('href',imageArray[state][0])
document.getElementById('imageBoxText').innerHTML = imageArray[state][1];
OK, so now what I need to do is write a function that can do this for multiple images, side by side, reading from a modified imageArray that looks like:
imageArray = {'questionOne': [['www.linktoimage1.com,'Legend for image1'],['www.linktoimage2.com,'Legend for image2']]}
The code should be able to handle up to three images, but I certainly wouldn't mind if it could do any more.
I tried to do it using a table to represent the images and used a for loop with the code from earlier. The image would never load, stuck on the spinner for ever and the images would all bunch up on one side of the screen.
Any help appreciated, thanks very much.
Well, I think I see what you're trying to do.
It sounds like you're trying to make a slideshow of some kind.
This is an example of how I would have done it.
Here's the jsfiddle so you can see what's going on. http://jsfiddle.net/VodkaTonic/4KWLr/
(function () {
var imageArray = {
link: [['http://i.imgur.com/7OfqRbF.jpg', 'http://i.imgur.com/AHbc6zO.jpg','http://i.imgur.com/gW144OQ.jpg'],['http://i.imgur.com/v0V8hrB.jpg', 'http://i.imgur.com/9l40vIT.png','http://i.imgur.com/ZXYUttz.png']],
label: [['Legend for image1','Legend for image2', 'Legend for image3'],['Legend for image4','Legend for image5', 'Legend for image6']]
},
doc = document,
question = 0,
img = doc.getElementsByClassName('images'),
links = doc.getElementsByClassName('links'),
label = doc.getElementsByClassName('label'),
button = doc.getElementById('button');
function add (state) {
var arr = imageArray.link[state],
arr2 = imageArray.label[state];
arr.forEach(function(value,index,array) {
img[index]['src'] = value;
links[index]['href'] = value;
});
arr2.forEach(function(value,index,array) {
label[index]['innerHTML'] = value;
});
question++;
}
window.addEventListener('load', add(question), false);
button.addEventListener('click', function () {
add(question);
}, false)
}());

JavaScript, How to change the background of a div tag every x seconds

I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:
HTML
<div id="bg_left"></div>
<div id="bg_right"></div>
CSS
body{
height:100%;
}
#bg_left{
height:100%;
width:50%;
left:0;
position:fixed;
background-position:left;
}
#bg_right{
height:100%;
width:50%;
right:0;
position:fixed;
background-image:url(http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png);
background-position:right;
}
JAVA SCRIPT
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ];
var img1 = bgimgs[id];
var img2 = bgimgs[id+1];
var cnt = 2;
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
id = id + 1;
if (id==cnt) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
$(document).ready(function() {
carousel_bg(0);
});
​
The background-images should be changing randomly, but they don't even change at all.
OK, I see the issue in your jsFiddle. Because you're passing a string to setTimeout() that string will be evaluated only at the top level scope. But, the function name you were passing is not at the top level scope (it's in an onload handler for the jsFiddle). So, I changed the way your JS is positioned in the jsFiddle so it is now at the top level scope. I also fixed up the logic for selecting an image and it now works here: http://jsfiddle.net/jfriend00/awVYP/
And, here's a cleaned up version that does not pass a string to setTimeout() (a much better way to write javascript) that passes a local function and uses a closure to keep track of the current index: http://jsfiddle.net/jfriend00/LVGNN/
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ]; // add images here..
function next() {
if (id >= bgimgs.length) {
id = 0;
}
var img1 = bgimgs[id];
id++;
if (id >= bgimgs.length){
id = 0;
}
var img2 = bgimgs[id];
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
setTimeout(next, 1000);
}
next();
}
$(document).ready(function() {
carousel_bg(0);
});
Previous comments on earlier version so of the OP's code:
$('#body')
should be:
$('body')
or even faster:
$(document.body)
Also, your jsFiddle shows a bit of an odd issue. Your CSS has a background image on the HTML tag, but your javascript sets a semi-transparent background image on the body tag. Is that really what you want?
For testing I added another image to the array so that we got some distinction in the sorting.
function carousel_bg(id) {
var bgimgs = [ 'http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png', 'http://presotto.daterrawebdev.com/d/img/burningman_bg.png', 'http://gallery.orobouros.net/var/albums/2012/NewYorkComicCon2012/Legend-of-Korra/nycc_20121013_164625_0041.jpg?m=1354760251' ]; // add images here..
var img1 = bgimgs[id+1];
var img2 = bgimgs[id];
var cnt = bgimgs.length; // change this number when adding images..
$('#bg_left').css("background-image", "url("+img1+")");
$('#bg_right').css("background-image", "url("+img2+")");
id = id + 1;
if (id== (cnt - 1) ) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
Two changes here:
For your total image count, I am retrieving the total count of images in the array dynamically instead of by hand (bgimgs.length)
In your conditional to reset the id value, subtract the total count by 1. Since JS has zero-based indexes, not doing this will get you an undefined error (a 3 item array will spit out a value of 4 in your original code on the last iteration).
While this code does loop through your array, it's not random. That's another topic.
For those not using JQuery, simply do the following:
document.body.style.backgroundImage="url(images/mybackgroundimage.jpg)";

Categories