Making a print of a canvas img - javascript

I am trying to create a button that when clicked:
opens a canvas img in a new window;
starts the print function;
closes the new page after using JS.
This is what I have so far:
function printCanvas() {
var canvas = document.getElementById("sidstemoned");
var img = canvas.toDataURL("image/png");
var newWin = window.open("");
newWin.document.write('<img src="' + img + '" />');
newWin.print();
newWin.close();
}
$(document).ready(function () {
$('#print_canvas').on('click', printCanvas);
});
Canvas:
<canvas
class='costumor_statistic col-lg-12 col-md-12 col-sm-12'
style='height:350px;'
id='sidstemoned'></canvas>
Button:
<button
class="btn btn-default hidden-print"
id="print_canvas">Print <span class="fa fa-print "></span></button>
The console prints this when I press the button:
Uncaught TypeError: Cannot read property toDataURL of null
at printCanvas
at HTMLButtonElement.
at HTMLButtonElement.dispatch (jquery.min.js:4)
at HTMLButtonElement.r.handle (jquery.min.js:4)

Does it work correct?
function printCanvas() {
var canvas = document.getElementById("canvasname");
var img = canvas.toDataURL("image/png");
var newWin = window.open("");
newWin.document.write('<img src="' + img + '" />');
newWin.print();
newWin.close();
}
UPD: Maybe you try find canvas before it was added to DOM. Try to wrap your onClick handler to $(document).ready
$(document).ready(function(){
$('#print_canvas').on('click', printCanvas);
});

The current problem is that the variable canvas you are using in the printCanvas function is null, which means that when you tried to fetch the element with:
document.getElementById("sidstemoned");
Nothing was found, and therefore in the second line, instead of accessing an element from the DOM, this is happening:
null.toDataURL("image/png");
null does not have a toDataURL property (or function), that is why you get that error. So just make sure that your variable canvas has an element associated to it, i.e. the id sidstemoned you are referencing exists in the document. You can verify that canvas has something by simply consulting its length property:
if(canvas.length !== 0) { /* remaining code goes here */ }
Also, non-directly related, you may want to delete the extra class attribute in the button (the one with a single costumor_statistic).

Related

I need to keep element reference to pass on

When the user clicks on <a> tag it calls a function like the following:
<a href="#" onclick="func1(this)">;
This function generates HTML for a modal that needs to reference the first button.
func1(elem) {
html='<div class="modaldiv">' +
'<a href="#" onclick="func2(e.srcElement)">'+
'</div>';
}
When the link inside the modal is clicked, func2() should save text into a data attribute inside the first link, but this is not working, returning:
"Uncaught SyntaxError: Unexpected identifier "
First, don't use inline HTML event handling attributes (onclick, onmouseover, etc.), here's why.
But, your actual problem is that you are not properly declaring your function.
This: func1(elem)
Needs to be this: function func1(elem)
Next, you <a> elements must have some content for someone to see and click on and they must then be closed, which you didn't have.
function func1(elem) {
html='<div class="modaldiv">' + 'click me too'+ '</div>';
document.body.innerHTML += html;
}
click me
If you rework your answer to use modern standards, the proper modern way to do this would be:
// Get references to DOM elements
var a1 = document.getElementById("firstAnchor");
a1.addEventListener("click", func1);
// Callback for first link:
function func1(e) {
// Store original source element
var src = e.srcElement;
// Formally create new elements and configure them
var d = document.createElement("div");
d.classList.add("modaldiv");
var a = document.createElement("a");
a.href = "#";
a.textContent = "Click me too!";
// By hooking up to a wrapper function, we can have that function
// pass arguments to the actual callback function:
a.addEventListener("click", function(){
func2(src);
});
// Add new elements to the document
d.appendChild(a);
document.body.appendChild(d);
}
function func2(firstSrc){
console.log("func2 invoked and e.srcElement from first link is: ", firstSrc);
}
click me

reference error not defined

create2.innerHTML = create2.innerHTML+ " <img onclick = 'a()' src =' "+ messages[msg].thumb + "' height='90' width='142'> </a> ";
function a (){
}
So I am trying to include an onlick event on image tag so that when it is click a function is called. However, I am getting the following error :
Uncaught ReferenceError: a is not defined onclick
Can somebody please explain why this is happening?
This is why using inline events is a bad idea. Your scope is window, so it looks for the click in the window. When the function is inside another, you have no access to it.
var img = document.createElement("img");
img.src = messages[msg].thumb;
img.style.height = "90px";
img.style.width = "142px";
img.onclick = a; //would be better to use addEventListener()
create2.appendChild(img);

how to add text and images together on a function load

I have a function in which when the function is called I need to have text and an image pop up. My javascript is:
function Upload(){
if(value !- ''){
$("#divValue").html("Uploaded: " + //i need to add an image here );
}
So where it says //I need to add an image here, this is where my image, lets say its tire.gif, needs to be added so when the javascript is called it displays the text and image together.
you can use document.createElement method to create a img Object and simply set the source and optional height and width, then add it to your div using "append":
var img = document.createElement('img')
img.src = //URL to your image
$(img).css('width','50px'); //set the width (optional)
$(img).css('height','50px'); //set the height (optional)
//finally append the newly created image object to your "DivValue"
$("#divValue").append(img);
Can you try this,
function Upload(){
var value="some value";
if(value != ''){
$("#divValue").html("Uploaded: <img src='../images/tire.gif' />" );
}
}
It is actually pretty straight forward. You just need to pass the tag inside the string that will replace the html.
Check this jsFiddle
But you just need to do:
$("#divValue").html("Uploaded: <img src=' PATH_TO tire.gif ' /> ");
Watch the difference between " and ' to avoid syntax problems.
Cheers.
You mean like this?
$("#divValue").html('Uploaded: ' + '<img src="image.jpg" alt=""/>');

JavaScript windows.onload or referencing new elements?

I'm trying to create a lightbox and I'm having trouble.
I think the problem is either because I have 2 window.onloads or because I'm trying to reference a newly created DOM element. I added some comments in the code below that explain what I'm trying to do.
//open lightbox
window.onload = showLargeImage;
function showLargeImage() {
var enlargeButton = document.getElementById("thumb1"); // thumb1 is a thumbnail you click to get the lightbox
enlargeButton.onclick = handleClick;
}
function handleClick() {
var lightboxContainerId = document.getElementById("lightboxContainer");
lightboxContainerId.innerHTML = '<div class="lightbox"><a class="reduceButton" href="#" ><img id="imageButton" class="largeImage" src="2012/images/web/web1.jpg" width="500" height="500" alt="Web Thumb 1"></a></div>';
} // the inner HTML creates the lightbox.
//close lightbox
window.onload = reduceImage; // i'm pretty sure that this windo.onload is the problem... or, that I'm referencing "imageButton" which is new to the DOM
function reduceImage() {
var reduceButton = document.getElementById("imageButton"); // you're supposed to click the big image in the lightbox to get close it.
reduceButton.onclick = handleReduceClick;
}
function handleReduceClick() {
var shadeId = document.getElementById("lightboxContainer");
shadeId.innerHTML = "say what"; // closing the lightbox simply strips everything out of the lightboxContainer
alert("oh yeah");
}
Here are a few reasons why your code is not working:
showLargeImage and reduceImage are missing invocation parentheses in the places where they are being assigned to window.onload. Without parentheses, window.onload is being assigned a function, but that function is not getting called. You should, for instance, have window.onload = showLargeImage();
As you suspected, the second window.onload is overwriting the first.
reduceButton is (as you also suspected) being assigned before it exists, causing an error.
Here is one solution that may work for you.
HTML:
<!DOCTYPE html>
<html><head><title></title>
</head><body>
View
<div id="lightboxcontainer"></div>
</body></html>
JavaScript:
window.onload = function() {
// click link to show
var enlargeButton = document.getElementById('thumb');
enlargeButton.onclick = function() {
var lightboxContainerId = document.getElementById('lightboxcontainer');
lightboxContainerId.innerHTML = '<img src="http://placehold.it/350x150"' +
'width="350" height="150 alt="Thumb 1">' +
'<p>Click image to hide.</p>';
};
// click image to hide
var reduceButton = document.getElementById('lightboxcontainer');
reduceButton.onclick = function() {
reduceButton.innerHTML = ''; // removes lightbox contents
};
};
Live demo: http://jsfiddle.net/ericmathison/BxwYY/7/
If the code is placed at the end of the <body> (or anywhere after your lightbox elements), just use this:
document.getElementById("thumb1").onclick = function () {
document.getElementById("lightboxContainer").innerHTML = '<div class="lightbox"><a class="reduceButton" href="#" ><img id="imageButton" class="largeImage" src="2012/images/web/web1.jpg" width="500" height="500" alt="Web Thumb 1"></a></div>';
document.getElementById("imageButton").onclick = function () {
document.getElementById("lightboxContainer").innerHTML = "say what";
alert("oh yeah");
};
}
This will do everything you want.

is it possible to display pictures in a popup.php window, using the src from the main page?

I have a page with pictures, which I want to displayed in a popup.php when clicking on them.
I want the popup window to display a picture(the one I'm clicking on), some text, and a print button.
I'm doing this on the page:
<img src="graphics/picture1.png" width="340" height="200" border="0"/>
In the JS file:
function popup()
{
window.open('popup.php', 'window', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
}
function showImg(img)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
}
And in the popup.php:
<img src="graphics/picture03.png" onload="showImg(this)" />
There should be an obvious way, but I can't find it.
I would think adding the image name and text content to the URL would be the obvious way.
popup.php?image=myImage.gif&text=Say%20something%20witty%20here
Well, you'll want to have your popup contain a holder for the image (which it seems like you already have), but you'll also need to have a holder for your text. Your popup.php should have something like <div id="textHolder"></div> - then your javascript function needs to accept the appropriate text as well as populate it into the textHolder div.
I'm not sure how you're calling these JS functions, or from where - so some of the code might need to change - it should be something to the tune of....
function showImg(img, textHolderObj, text)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
textHolderObj.innerHTML= text
}
If is that simple, you could create it:
var win = window.open('', 'win', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
var img = win.document.createElement('img');
img.src = 'image.png';
img.alt = 'Some text';
var label = win.document.createElement('p');
label.innerHTML = 'Some text';
var button = win.document.createElement('a');
button.href = 'javascript:window.close()';
button.innerHTML = 'Close';
win.document.body.appendChild(img);
win.document.body.appendChild(label);
win.document.body.appendChild(button);
I don't get the question too well. You want to access a function that was defined in the page that opened a popup? You should be able to use opener.showImg(this)
your popup has no idea what image you clicked on. you need to do this:
onClick="popup('imgSrc')"
and in your window reference:
window.open('popup.php?imgSrc='+imgSrc, ...
then... your popup window has to run off of url vars, but php now knows what its looking for:
<?php echo '<img src="' . $_GET["imgSrc"] . '" />'; // this is going to load the image, so you don't need the onLoad()
It is possible to create a new popup window using a variable
top.mydocument=window.open('','window','toolbar=no,location=no,
status=no,menubar=no,scrollbars=no,resizable=no,
width=520,height=400,left=350,top=100');
and then use document.write to write the content:
top.mydocument.document.write(
'<html><head></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+'imageName/imagePath.png'
+'</body></html>'
)
Make sure you close it.
top.mydocument.document.close()

Categories

Resources