Html2Canvas and Canvas2Image not work on page - javascript

I have this simple code to save html as image:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/html2canvas.js"></script>
<script src="js/canvas2image.js"></script>
<script>
$('#save').click(function () {
var elem = $('#element').get(0);
var leba = "600";
var ting = "400";
var type = "bmp";
var name = "temp"
html2canvas(elem).then(function (canvas) {
var cWidth = canvas.width;
var cHeight = canvas.height;
var img = Canvas2Image.convertToImage(canvas, cWidth, cHeight);
$('#preview').after(img);
Canvas2Image.saveAsImage(canvas, leba, ting, type, name);
})
})
</script>
<div id="element"
style="width: 600px; height: 450px; background-color: aquamarine; margin: 30px auto; text-align: center">
<h1>Screenshot</h1>
<input type="text" style="background-color: aliceblue; border: 1px solid #aaaaaa; color: #333333">
</div>
<div style="text-align: center">
<button id="save">Salva</button>
<p id="preview"></p>
</div>
</body>
</html>
I want to have a preview of the screenshot and save it on click, but when I click nothing happens.
The three files containing the three scripts are correctly loaded, I'm using visual studio code and the links are correct, but despite the attempts, I can't get the image.
I also tried to put the js links directly, but without success, I moved the scripts directly into the HTML tag (I know it's useless), but my page doesn't give any results.

For saving the canvas as image you can go through the below change. I dont think so, that you need a library to save the file.
html2canvas(document.querySelector("#element")).then(function (canvas) {
var dataURL = canvas.toDataURL("image/jpeg", 1.0);
var a = document.createElement('a');
a.href = dataURL;
a.download = 'untitled.jpeg';
document.body.appendChild(a);
a.click();
})
And for the complete reference you can visit the CodePen link added below
https://codepen.io/mukeshmohan/pen/ymvQjV
And its recommended to wrap your code inside a document ready.
$( document ).ready(function() {
// your script goes here
});
which will make the jquery to wait till the dom rendering completes, that allows a safe and clean event handling.

You need to wrap your code in a
$( document ).ready()
block
Take a look here

Related

PDF Generation from HTML page using JavaScript or Jquery Library or Plugin

I am trying to convert an html page to PDF which contains images and some data-tables which as designed using css styles.
I have tried JSPDF and html2canvas libraries but the images don't show up in PDF and also they don't allow me to create PDF on long pages as my html is dynamic and it could grow into four pages.
I have searched so many forum's online but unable to find anything which resolves my issue.
The site in which i am implementing is shopify site. So any clue with this reference might help.
Any sort of help will be highly thankful.
Thanks
check at this link if it can be usefull for you on codepen
https://codepen.io/massimo-cassandro/pen/qOrJNx
<html>
<!-- donot consider this i put it just to allow the link-->
<html/>
Transform the content of your html into image and then transform it into PDF :
https://html2canvas.hertzen.com/
https://parall.ax/products/jspdf
var doc = new jsPDF();
var specialElementHandlers = {
'': function (element, renderer) {
return true;
}
};
$('#btn-download').click(function () {
html2canvas($('#container').html).then(function (canvas) { DownloadPDF(canvas) });
});
function DownloadPDF(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10, parseInt($(canvas).attr('width')) / 9, parseInt($(canvas).attr('height')) / 9);
doc.save('name.pdf');
}
#test
{
width: 500px;
height : 500px;
background-image: url("https://www.wikichat.fr/wp-content/uploads/sites/2/comment-soigner-une-plaie-dun-chat.jpg");
background-size: contain;
background-repeat: no-repeat;
}
#btn-download
{
cursor:pointer;
position:fixed;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<div id="btn-download">Download</div>
<br/>
<div id="container">
<div id="test">
</div>
</div>
</body>
</html>

how to change image when scrolling webpage [html, javascript]

Hi i need to modify java script that will by changing fixed image.
In for example:
when page is loaded then image will by on right site. Next after scrolling down page image should be changed to next one for each e.g. 100px. Images need to by loaded from image list or something similar.
I have found java script that make something similar to this. [Instead of creating images of numbers i need to load my own images]
<!DOCTYPE html>
<html>
<head>
<style>
html,body {
height: 400%;
background: white;
width: 100%;
}
.show {
width: 100px;
height: 100px;
position: fixed;
top: 300px;
right: 20px;
background: lime;
}
</style>
</head>
<body>
<img class="show" alt="0" src="img0.jpg" />
Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
<script type="text/javascript">
var lastI
$(window).scroll(function() {
var scrollTop = $(this).scrollTop()
console.log(scrollTop)
var i = (scrollTop / 10).toFixed(0)
if (i !== lastI)
$(".show").attr({
"src": "img" + i + ".jpg",
"alt": i
})
lastI = i
})
</script>
</body>
</html>
Update:09.11.2017
Ok, I manage this code to work. What should I do it was to setup right path to image files like in my case ("src": "test/" + i + ".jpg",) where my images are in "test" folder, and change names of images [1.jpg, 2.jpg and so on].
You can easyli change your image with Native scroll event, without using JQuery :
You can see how to use native scroll event here
<body>
<!-- This is an image with a 'show' id -->
<img id="show" alt="0" src="img0.jpg" />
<script type="text/javascript">
/* this capture the `scroll event`*/
window.addEventListener('scroll', function(e) {
/* This generate a image name in case with scroll position (ex img1.jpg) */
let bgImage = 'img' + (window.scrollY / 10 ).toFixed(0) + '.jpg';
/* This specify the path where are your images list */
let bgImagePath = '../images/' + bgImage;
/* This get your element (img) with id `show` and change this background image by the path include in `bgImagePath` variable */
document.getElementById('show').style.backgroundImage = bgImagePath;
});
</script>
</body>
Native background image explain here
Native getElementById explain here
This sample of code do not use JQuery :) Just native Javascript : you van remove this lines in your code :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
Hope I help you.
I'am not sure, try this one:
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 100) {
$('.Classname').css("background-image","../images/image.png");
} else {
$('.Classname').css("background-image","none");
}
});

JavaScript isn't read correctly in HTMLQuestion

I made a simple application using the code from this and ran it to test it on the worker sandbox MTurk site. It works perfectly when using the code shown in the answer, but if I try to create an object and place the function and variables in the object, the buttons won't work on the sandbox site but will work when opening the .html file in a browser. Additionally, adding comments will produce the same effect. The code I have is this:
<?xml version="1.0"?>
<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
<HTMLContent><![CDATA[
<!DOCTYPE html>
<html>
<head>
<style>
#thediv {
align-self:flex-start
margin:0 auto;
height:1050px;
width:750px;
overflow:auto;
}
img {
position: static;
left: 50%;
top: 50%;
}
</style>
</head>
<body>
<input type='button' value ='-' onclick='zoom(0.5);'/>
<input type='button' value ='+' onclick='zoom(2);'/>
<div id="thediv">
<img id="pic" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Nokota_Horses_cropped.jpg"/>
</div>
<script type="text/javascript">
var zoomLevel=1;
var maxZoomLevel=2;
var minZoomLevel=1;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel++;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel--;
}else{
return;
}
}
wid = img.width;
ht = img.height;
img.style.width = (wid*zm)+"px";
img.style.height = (ht*zm)+"px";
}
</script>
</body>
</html>
]]>
</HTMLContent>
<FrameHeight>450</FrameHeight>
</HTMLQuestion>
Is there a reason certain things will work in browser but not in the MTurk sandbox site?
I just tested creating a HIT like this and it worked for me.
Unrelated to the JavaScript, note that you will need to include at least one named input (eg ) in order for Workers to submit the HIT.
What browser are you testing in?

iframe parent document element

This should work according to all the stuff I've looked up, but it just doesn't.
I have a html with a document. It has a div, which contains a specific element which I want to access.
<li>FAQ</li>
The html document also contains an iframe with the FAQ.html, which has the following loadup code:
<script>
function loaded() {
parent.document.getElementById("Faq").style.color = "green";}
</script>
However, nothing happens. What am I doing wrong?
The error console reports nothing which could facilitate my analasys.
EDIT:
Here's a basic concept.
https://dl.dropbox.com/u/32831239/Screenshots/htmlstructure.png
(Unfortunately stackoverflow doesn't let me post images as of now)
The left div should serve as a nav bar. Upon page load, the li entry should be marked with a color (e.g. green).
Use onload event of the body of FAQ.html to invoke loaded function
<html>
<head>
<script>
function loaded() {
alert("Hello !"); //alert to check if this is being invoked.
parent.document.getElementById("Faq").style.color = "green";
}
</script>
</head>
<body onload="loaded();" >
...
</body>
</html>
Or just remove the function (no need to use body onload event)
<script>
parent.document.getElementById("Faq").style.color = "green";
</script>
<iframe src="test1.html"
style="float: right;
width: 260px; height: 130px;
margin-left: 12px; border: 1px solid black;"
name="#boogiejack">
Alternative Content
</iframe>
Test1.html content
<li>FAQ</li>
<script type="text/javascript">
function loaded() {
document.getElementById("Faq").style.color = "green";}
</script>
You could use the following in your parent
var iframe = document.createElement("iframe");
iframe.src = urlToYourIframe;
// if this is IE then use attachEvent
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
parent.document.getElementById("Faq").style.color = "green";
});
} else {
iframe.onload = function(){
parent.document.getElementById("Faq").style.color = "green";
};
}
var el = document.getElementById("iFrameContainer");
el.appendChild(iframe);​

Javascript: Event does not fire unless element appended to document.body

I dynamically create an element (div) in javascript, on which i register an event listener:
var tooltip = document.createElement('div');
tooltip.onclick = function() { alert('hello'); }
Now, if I attach this element to the document body:
document.body.appendChild(tooltip);
all is well and the event is captured. However (for positioning purposes) i want to attach this element to a (static) sub-element within my page, e.g:
document.getElementById('id').appendChild(tooltip);
and the element is generated and positioned correctly - but the onclick event now is no longer captured. Any thoughts? This is x-browser, so i must be missing something.
Thanks, Don.
You're creating not only one but MANY divs.
Try this instead(I hope you don't mind but I fixed the HTML and CSS too):
<html>
<head>
<script type="text/javascript">
function makeDiv() {
if(!document.getElementById('tooltipDiv')){
var tooltip = document.createElement('div');
tooltip.id = "tooltipDiv";
// Give our tooltip a size and colour so we can see it
tooltip.style.height = '200px';
tooltip.style.position = 'absolute';
tooltip.style.width = '200px';
tooltip.style.backgroundColor = '#eee';
// Register onclick listener
tooltip.onclick = function() { alert('hello'); }
//tooltip.addEventListener("click", function(){ alert('hello'); }, false);
// *** Comment one of these out: ***
//document.body.appendChild(tooltip);
document.getElementById('myDiv').appendChild(tooltip);
}
}
</script>
</head>
<body>
<div id="myDiv"
onmouseover="makeDiv();"
style="position: relative; top: 100px; left: 100px; border: 1px solid red; width: 200px;">
<span>my div text</span>
</div>
</body>
</html>
Maybe you need to register the event handler after appending?
Your code works fine for me on firefox 3.0.5 and IE7. Are you sure your example is correct?
Ok all, here is my code, apologies for the delay. A version with a work-around is posted underneath:
<html>
<head>
<script type="text/javascript">
function makeDiv() {
var tooltip = document.createElement('div');
// Give our tooltip a size and colour so we can see it
tooltip.style.height = '200px';
tooltip.style.position = 'absolute';
tooltip.style.width = '200px';
tooltip.style.backgroundColor = '#eee';
// Register onclick listener
tooltip.onclick = function() { alert('hello'); }
// *** Comment one of these out: ***
//document.body.appendChild(tooltip);
document.getElementById('myDiv').appendChild(tooltip);
}
</script>
</head>
<body>
<div id="myDiv"
onmouseover="makeDiv();"
style="position: relative; top: 100px; left; 100px; border: 1px solid red; width: 200px;">
<span>my div text</span>
</div>
</body>
</html>
===================================
OK - so this works:
<html>
<head>
<script type="text/javascript">
function makeDiv() {
var tooltip = document.createElement('div');
// Give our tooltip a size and colour so we can see it
tooltip.style.height = '200px';
tooltip.style.position = 'absolute';
tooltip.style.width = '200px';
tooltip.style.backgroundColor = '#eee';
// Register onclick listener
tooltip.onclick = function() { alert('hello'); }
// *** Comment one of these out: ***
//document.body.appendChild(tooltip);
document.getElementById('container').appendChild(tooltip);
}
</script>
</head>
<body>
<div id="container" style="border: 1px solid blue; float: left; ">
<div id="myDiv"
onmouseover="makeDiv();"
style="position: relative; border: 1px solid red; width: 200px;">
<span>my div text</span>
</div>
</div>
</body>
</html>
Here is some code to remove the tooltip for onmouseout.
Give your toolTip an ID when creating it:
toolTip.setAttribute('id','toolTip');
Then for onmouseout
function removeDiv(container) {
var toolTip = document.getElementById('toolTip');
document.getElementById(container).removeChild(toolTip);
}

Categories

Resources