How to create a popup in Javascript? - javascript

I'm working on a web application using JSF and Javascript. I have a question about how to open a pop-up and add information into it.
Indeed, i'm using html2canvas to get the image of the content of a HTML page.
This is the code of my js :
function openPopupWithScreenshot(){
html2canvas($('#contentBody'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
window.open(img);
}
});
}
And the code of my button in JSF:
<h:commandButton value="#{bundle.button_print}" onclick="openPopupWithScreenshot();"/>
The code works perfectly, when i click on the button, a popup appears with my image. But my problem is I want to add more information (stored in a Javabean) into my popup.
Schematically, i want that my popup displays my image and a String stored in my Javabean. I'm a noob in javascript and i don't know how to do.
Could you help me please?
Thank you.
EDIT :
I have tried this :
function ouvrirPopupAvecImprEcran(){
html2canvas($('#contentBody'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
var newImg = window.open(img);
newImg.document.write("<title>TITLE</title>");
newImg.document.write("<img src='"+ img.src +"'/>");
newImg.document.write("<p>TEST</p>");
}
});
}
My popup appears correctly but my image is not display because it doesn't find the source of my image. How could i modify this?

You was almost there, try this:
function ouvrirPopupAvecImprEcran(){
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var newImg = window.open();
newImg.document.write("<title>TITLE</title>");
newImg.document.write("<img src='"+ img +"'/>");
newImg.document.write("<p>TEST</p>");
}
});
}
The image you created from canvas here var img = canvas.toDataURL("image/png"); was not the HTML Element img. It was a string with data: URL, it's like an image encoded into string.
To understand it better you could look at HTMLCanvasElement#toDataURL() method here http://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement

Related

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

How to generate "screenshot" of html div with external images?

I have a HTML div with external images. (The following is an example, but in the actual case I am using Amazon S3, so downloading and storing the image on the same server is not an option) Currently I am using html2canvas to convert the div to image. However, the external image is always replaced by a blank space.
The code I use to capture the image:
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
Edited: jsfiddle: https://jsfiddle.net/0y2zxxL8/3/
I may use other library. I may also do that in backend. (I am using PHP + laravel 5 for backend) Is there a way I can generate a "screenshot" of the HTML div with external images?
Update The current answer are working after editing. Yet, for my actual use, there will be multiple image with their position set by the user by drag and drop. I can still get the position, but it would be better for me if it is possible to not set the position specifically.
Your JSFiddle given ReferenceError: Canvas2Image is not defined while hit on 'Save PNG' button. So check your code(not fiddle) for same error.
UPDATE
See this JSFiddle example as reference. May this one will help you.
UPDATE 2
I place some code into your one, check it out. Hope this will be your solution..!
Working result with FF v44 and its working. Taken snap with JSFiddle code
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
var context=canvas.getContext("2d"); // returns the 2d context object
var img=new Image() //creates a variable for a new image
img.src= "http://lorempixel.com/400/200/"; // specifies the location of the image
context.drawImage(img,0,50); // draws the image at the specified x and y location
// Convert and download as image
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
UPDATE 3 (12/29/2016) JSFiddle
After research, found that the problem is because we are only assigning the image source which is only pass message to the browser to retrieve the data.
Further image element is may be not really accessible with the browser when click to draw canvas from it. We are just tell code to load it and it's done.
Change code to solve OP's facing chrome issue like below:
img.onload = function() {
context.drawImage(img, 0, 50);// draws the image at the specified x and y location
}
UPDATE 4 JSFiddle
Make image position dynamic based on OP requirement.
onrendered is no longer working..
i solved this problem by adding "allowTaint" option
{ allowTaint: true }
2018 solution:
html2canvas(document.getElementById('result'), { allowTaint: true }).then(function (canvas) {
document.body.appendChild(canvas);
});
You may try to scan the image source for external urls and change them to your website and load them with php.
Something like
$(function() {
var imageproxy = "http://example.com/imageproxy.php"; //Change this
var mydomain = new RegExp(location.host);
$("#btnSave").click(function() {
$("#widget").find('img').each(function(){
var img_src = $(this).attr('src');
if(!mydomain.test(img_src)){
$(this).attr('src', imageproxy + "?url=" + encodeURIComponent(img_src));
}
});
html2canvas($("#widget"), {
onrendered: function(canvas) {
var link = $('<a target="_blank">Download</a>');
link.attr('download', 'test.png');
link.attr('href', canvas.toDataURL());
$("#btnSave").after(link);
}
});
});
});
imageproxy.php
<?php
if(!empty($_GET['url'])){
$url = urldecode($_GET['url']);
$img_type = "image/jpeg";
$chunks = explode('.', $url);
if(is_array($chunks) && count($chunks) > 1){
$ext = end($chunks);
switch ($ext){
case 'jpg':
case 'jpeg':
$img_type = "image/jpeg";
break;
case 'png':
$img_type = "image/png";
break;
case 'gif':
$img_type = "image/gif";
break;
}
}
$img = file_get_contents($url);
header ("Content-Type: $img_type");
echo $img;
}
note: php script is very simple, image detection is not working 100%, this is just ti give you an idea. If you use some php image libs to load and get image type you can do this just with few lines of code. you may also try with "php readfile".

MVC using image path for canvas on page with JavaScript

<canvas id="myCanvas" width ="320" height="260">
<img src="#Model.img.path" id="img" >
I am trying to use MVC model to create "update news" page.
News has an image and i am using canvas to upload images that because users can edit images with editor based on canvas process. Creating news is Ok.But when updating news, i would like to see image in my canvas that already created . i took my entity and pass it to the View of "update news"-news includes img path- but i cant figure out how can i use this path to show my image in the canvas element.
Thanks alredy.
Sorry for my english.
var img = new Image()
img.onload = function () {
ctx.drawImage(img, 0, 0, 1600, 900);
}
img.src = "#Model.image.path";
I just use this simple code. It works.
for drawing image in canvas with javascript , you can use this function:
function drawDataURIOnCanvas(strDataURI, canvas) {
"use strict";
var img = $("#img");
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0);
});
}
for calling :
drawDataURIOnCanvas('#Model.img.path',$("#myCanvas"));

Html2canvas only capture screensize and not the entire div container

I am trying to capture whole "div container" in one image using html2canvas. For some reason im only getting the part which shows on my screen. But I have a horizontal scroll on the div so I would like to capture whats not on my screen aswell but the content inside the div.
Is that possible? Right now my div is 5000px width, can i capture it all in one image somehow?
Here is my javascript code for html2canvas:
$(function() {
$("#btnSave").click(function() {
});
html2canvas($("#container_wrapper_anatomy"), {
onrendered: function(canvas) {
theCanvas = canvas;
var dataUrl = canvas.toDataURL();
window.open(dataUrl, "toDataURL() image", "width=100%, height=100%");
canvas.toBlob(function(blob) {
saveAs(blob, "container_wrapper_anatomy.jpg");
});
}
});
});
});
Thanks in advance.

Canvas.toDataURL() returns a file without extension

I'm converting an HTML canvas into a jpg when a save button is clicked. I use the code below:
$('#save').click(function(e){
var canvas = $('#myCanvas')[0];
var image = canvas.toDataURL("image/png").replace("image/png","image/octet-stream");
window.location.href=image; // it will save locally
});
Unfortunately, I download file without any extension. What I want is when I click the download button, The browser must download file from the page with a file extension.
Thanks
#K3N's answer didn't work for me because as mentioned:
Ideally you set the href before the click somehow.
I built on top of it and did this and it works great.
var btnSave = document.getElementById('btnSave');
btnSave.addEventListener('click', function() {
var image = photo.toDataURL("image/png");
var anchor = document.createElement('a');
anchor.setAttribute('download', 'myFilename.png');
anchor.setAttribute('href', image);
anchor.click();
});
Assuming your #save element is an anchor tag (<a ...></a>) you can do this:
$('#save').click(function(e){
var canvas = $('#myCanvas')[0];
var image = canvas.toDataURL("image/png");
$('#save').attr({
'download': 'myFilename.png', /// set filename
'href' : image /// set data-uri
});
});
Ideally you set the href before the click somehow.
You should use:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
for loading,you need to use:
document.write('<img src="'+img+'"/>');

Categories

Resources