html2canvas change div - image

I have a issue with html2canvas showing the screenshot in a canvas div.
Actually the picture will be show in
<div id="content"> </div>
But i like to show the code in my canvas
<div id="content">
<canvas id="myimage"> HERE I LIKE TO SHOW THE IMAGE</canvas>
</div>
In the inline javascript i can change the div container-id, but i dont know how to change the code to get the image in the canvas element.
<script type="text/javascript">var date=new Date();var message,timeoutTimer,timer;var proxyUrl="http://urlcanvas.appspot.com";function addRow(a,c,d){var b=$("<tr />").appendTo($(a));b.append($("<td />").css("font-weight","bold").text(c)).append($("<td />").text(d))}function throwMessage(b,a){window.clearTimeout(timeoutTimer);timeoutTimer=window.setTimeout(function(){message.fadeOut(function(){message.remove()})},a||2000);$(message).remove();message=$("<div />").html(b).css({margin:0,padding:10,background:"#000",opacity:0.7,position:"fixed",top:10,right:10,fontFamily:"Tahoma",color:"#fff",fontSize:12,borderRadius:12,width:"auto",height:"auto",textAlign:"center",textDecoration:"none"}).hide().fadeIn().appendTo("body")}$(function(){$("#recommended a").click(function(c){c.preventDefault();$("#url").val(this.href);$("button").click()});var a,b;$('input[type="button"]').click(function(){$(a.contentWindow).unbind("load");$(a).contents().find("body").html2canvas({canvasHeight:b.body.scrollHeight,canvasWidth:b.body.scrollWidth,logging:true})});$("#getscreenshot").click(function(d){d.preventDefault();$(this).prop("disabled",true);var c=$("#url").val();$("#contentx").append($("<img />").attr("src","loading.gif").css("margin-top",40));var f=document.createElement("a");f.href=c;$.ajax({data:{xhr2:false,url:f.href},url:proxyUrl,dataType:"jsonp",success:function(e){a=document.createElement("iframe");$(a).css({visibility:"hidden"}).width($(window).width()).height($(window).height());$("#contentx").append(a);b=a.contentWindow.document;b.open();$(a.contentWindow).load(function(){var g=$(a).contents().find("body"),h={onrendered:function(j){$("#contentx").empty().append(j);$("#getscreenshot").prop("disabled",false);$("base").attr("href","")},allowTaint:true,taintTest:false,flashcanvas:"src/flashcanvas.min.js"},i=html2canvas(g,h)});$("base").attr("href",f.protocol+"//"+f.hostname+"/"+f.pathname);e=e.replace("<head>","<head><base href='"+f.protocol+"//"+f.hostname+"/"+f.pathname+"' />");if($("#disablejs").prop("checked")){e=e.replace(/\<script/gi,"<!--<script");e=e.replace(/\<\/script\>/gi,"<\/script>-->")}b.write(e);b.close()}})})});</script>

Here is a good reference create screenshot of webpage using html2canvas (unable to initialize properly) Hope it will help.

If i understood well you need to append the canvas like this:
html2canvas(document.getElementById("content"), {
onrendered: function(canvas) {
document.getElementById("content").appendChild(canvas);
}
});

Related

Image not able to load when using p5js outside of online editor

I am using p5js and I am trying to load and display some images in my directory. I am trying to use the loadImage() method in my preload function to load an image. However, when I run the program, I get these errors
Fetch API cannot load file:///Users/mainuser/Documents/school/Senior/FinalProject/imgs/arms_up.png. URL scheme "file" is not supported.
🌸 p5.js says: It looks like there was a problem loading your image. Try checking if the file path (imgs/arms_up.png) is correct, hosting the file online, or running a local server. (More info at https://github.com/processing/p5.js/wiki/Local-server)
TypeError: Failed to fetch
at fetch (p5.js:28096)
at p5._main.default.loadImage (p5.js:80673)
at p5.js:62949
at preload (script.js:118)
at p5._start (p5.js:62905)
at new p5 (p5.js:63261)
at _globalInit (p5.js:62189)
My imgs folder is within the same folder as my index.html
My guess is that fetch() might need an actual URL instead of a file path.
Anybody else run into this problem? I've attached my code below (i took out irrelevant code). Thank you!
index.html
<!DOCTYPE HTML>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.3.1/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#teachablemachine/pose#0.8/dist/teachablemachine-pose.min.js"></script>
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.0/lib/p5.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Pose Game</h1>
<button type="button" onclick="init()">Start Game!</button>
<button type="button" onclick="restart_game()">Restart Game</button>
<div id="main-div">
<div id="flex-div">
<div id="webcam-div">
<canvas id="canvas"></canvas>
</div>
<div id="p5-div"></div>
</div>
</div>
</body>
</html>
script.js
let arms_up_png;
let left_arm_up;
let right_arm_up;
function preload() {
arms_up_png = loadImage("imgs/arms_up.png");
}
function setup() {
var canvas = createCanvas(400, 400);
canvas.parent('p5-div');
}
function draw() {
background('green');
image(arms_up_png, 50, 50, 20, 20);
}
You are correct that fetch() will not work with local file paths, and because p5js needs to load the contents of the image file in order to display it you also cannot use local file paths with the p5js loadImage() function. In order to run your sketch locally you will need to use a local web server. The Visual Studio Code Live Server extension is quite handy for this purpose.

How to put p5.js canvas in a html div

I am trying to add p5.js to the background of one section in my webpage. I am new to javascript and can't figure out how to bind the two parts together.
You need to add code in your setup.
Make sure you have the function in a script tag in the html as well.
Note you do not add # in the .parent().
var myCanvas = createCanvas(winWidth, winHeight);
myCanvas.parent("idnameofdiv");
if you are inserting multiple p5js canvas in one page and are already using the form new p5(sketch), you can just pass the id of your div as second parameter, like new p5(sketch, idnameofdiv)
Because the function sketch should be unique (if you don't use an IIFE), I like to put the id in the name of the sketch function as well
function sketch_idnameofdiv(p) {
p.setup = function () {
p.createCanvas(400,400);
}
p.draw = function () {
// stuff to draw
}
}
new p5(sketch_idnameofdiv, 'idnameofdiv')
if you don't need to insert multiple p5js canvas in one page, I guess you are looking for Michael Paccione's answer
P5.js gives you an html canvas that you can use for positioning your sketch.
Here is an example of using a canvas as the background of a div:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:-1;
}
</style>
</head>
<body>
<h1>Heading</h1>
<p>paragraph 1</p>
<p>paragraph 2</p>
<script src="processing-1.4.1.min.js"></script>
<div id="canvasContainer">
<canvas data-processing-sources="rectangles.pde"></canvas>
</div>
</body>
This is Processing.js instead of P5.js, but the idea is the same. Try googling something like "html canvas as background" for a ton of results. Try something out, and post an MCVE if you get stuck.
To be more detailed about the answer:
function setup() is a function which executes ojnly once at the startup.
function draw() is a function which executes after setup() and it reloads on every frame of the picture.
The code goes like this:
<!DOCTYPE html>
<html>
<head>
<title>P5.js Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<script>
function setup() {
var canvas = createCanvas(400, 400);
canvas.parent('canvasForHTML');
}
function draw() {
background(127);
}
</script>
</head>
<body>
<h1>Canvas for visualization</h1>
<div id="canvasForHTML"></div>
<p>Move your mouse around to see circles.</p>
</body>
</html>
Check this:
https://jsfiddle.net/sugandhnikhil/74Ltdy8z/1/

javascript function that needs to get div id from img onclick

I have a javascript function that I need to give her an 'ID' of div from onClick img tag
Is there any one that can help me I don't know what to do:
Html:
<img onclick="imgClicked"></img>
<div id="foo">...</div>
Javascript:
<script type = "text/javascript">
window.imgClicked = function(){
var div = document.getElementById("foo");
...//do anything you want...
}
</script>
You can find the div , on which the image is clicked by using event.target.nodeName
Setup an click event handler for Image, then u can use above to find out the div of the image clicked.hope it helps..

Dynamically inserting content within same page rather then going to a new page

EDIT italics = more detailed explanation added to the question. Thanks.
I'm building a jQuery Mobile site which has a Gallery section.
The gallery has a series of thumbnails on the top of the screen.
Users click on the thumbnail to load in new content, that being a larger image, text, and potentially audio on some of them.
It's at this point that I'm not sure what to do: the way jQuery Mobile works, it's geared towards loading new pages, or views. But I just want to inject new content in a container on the current page.
To be clear, when the user clicks on another thumbnail, a new image replaces the content of the container with new content.
I have two questions:
I'm not sure how to structure the dynamic content. I was thinking i'd create an html file for each item, which as a rule always contains a title, information and sometimes, audio.
I'm not sure how to script this functionality in jQuery Mobile. It's obviously Ajax, but I'm not familiar with it yet, especially since jQuery Mobile has it's own methods in place already which seems to redefine behaviors in a way that's contradictory to this approach described here.
Here is a code explanation of what i'm trying to do:
<!-- Galleries -->
<div data-role="page" id="galleries">
<div data-role="content" role="main">
This is the Selection UI, if i click on thumb2.jpg, it'd
fill #content-holder with the whatever html is in content2.php
<div id="thumb-carousel">
<img src="thumb1.jpg">
<img src="thumb2.jpg">
<img src="thumb3.jpg">
<img src="thumb4.jpg">
<img src="thumb5.jpg">
<img src="thumb6.jpg">
<img src="thumb7.jpg">
<img src="thumb8.jpg">
<img src="thumb9.jpg">
</div>
<!-- This is the container, currently it's filled
with the kinda stuff i need to put in it. -->
<div id="content-holder">
<img src="myimage1.jpg"/>
<p>Artwork Title</p>
<p>Caption</p>
<audio>//mp3</audio>
</div>
</div>
</div>
//remember to use event delegation because you never know when the page will be in the DOM
$(document).delegate('#galleries', 'pageinit', function () {
//bind a `click` event handler to each thumbnail link
$('#thumb-carousel').children().bind('click', function () {
$.ajax({
url : $(this).attr('href'),
success : function (serverResponse) {
//select the container,
//then fade it out,
//change it's HTML to the response from the AJAX request,
//and fade it back in
$('#content-holder').fadeOut(500, function () {
$(this).html(serverResponse).fadeIn(500);
});
},
error : function (jqXHR, textStatus, errorThrown) {
//remember to handle errors so your page doesn't seem broken to the user
}
});
//prevent the default behavior of the link, which is to navigate to the `href` attribute
return false;
});
});
This expects your server-response to be valid HTML markup that is ready to inject into the DOM, meaning no <html> or <body> tags, just what you want to add to the DOM:
<img src="..." />
<span>TITLE</span>
<audio src="..."></audio>
Here are some docs for ya:
$.ajax(): http://api.jquery.com/jquery.ajax
.closest(): http://api.jquery.com/closest
.fadeIn(): http://api.jquery.com/fadein

printing jquery colorbox content

I am using colorbox to AJAX some external HTML onto a page.
My client wants to print this content direct from the page, therefore i used a print CSS loaded into the head of the document with colorbox's onComplete event hook.
The content that is loaded is a raft of legacy tables with inline styles which i can't seem to overwrite with the print CSS and when i view by media type the layout looks broken.
I put this down to only retrieving a chunk of the HTML with jQuery .find() rather than the whole page.
Would it be best to use an iframe with colorbox and load the whole HTML document including header. I assume this would preserve the layout better rather than retrieving a chunk.
I am not sure how to print the iframe's content. When i tried it printed an extremely small snapshot of the whole page with the iframe in the middle.
Am a bit lost on this one.
The jQuery i am using is as follows:
$('table.pricing > tbody > tr > th > p.price_report > a').colorbox({
title: "Price report",
transition: "elastic",
innerWidth: "733px",
innerHeight: "699px",
opacity: "0.5",
onComplete:function(){
// Ajax call to content
// insert Print CSS into head of document
}
});
The print CSS that is loaded merely hides the body content and then displays everything under #colorbox.
Apologies all the proper code is at work.
1) I would suggest switching to the "inline" colorbox option (but you don't have to):
<script type="text/javascript">
$(document).ready(function(){
$(".pricing").colorbox({width:"733px", height:"699px", iframe:false, open:true, overlayClose:true, opacity:.5, initialWidth:"300px", initialHeight:"100px", transition:"elastic", speed:350, close:"Close", photo:false, inline:true, href:"#price_report"});
});
</script>
2) Now add your html including the javascript and code to write your printable area:
<div style='display: none'>
<div id='price_report' class='pricing'>
<script type="text/javascript">
//<!--
function ClickHereToPrint(){
try{
var oIframe = document.getElementById('ifrmPrint');
var oContent = document.getElementById('pricingPrintArea').innerHTML;
var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
if (oDoc.document) oDoc = oDoc.document;
oDoc.write("<html><head><title>My Printable Pricing Report!</title>");
oDoc.write("<link rel='stylesheet' href='link-to-my-styles/style.css' type='text/css' />");
oDoc.write("</head></body><body onload='this.focus(); this.print();' style='text-align: left; font-size: 8pt; width: 432pt;'>");
oDoc.write("<h3>My Pricing Report</h3>");
oDoc.write(oContent + "</body></html>");
oDoc.close();
}
catch(e){
self.print();
}
}
//-->
</script>
<iframe id='ifrmPrint' src='#' style="width:0pt; height:0pt; border: none;"></iframe>
<div id="pricingPrintArea">
<div class="myreport">
<p>Hello, I am a pricing report!</p>
</div>
</div>
</div>
</div>
3) Now add the print button wherever you wish:
<div id="print_btn">
<a href="#" onclick="ClickHereToPrint();" style="cursor: pointer;">
<span class="print_btn">
Click Here To Print This Report!
</span>
</a>
</div>
Note, the blank iframe included is where the javascript will write your printable area. You will also notice in the javascript that you can add a stylesheet, inline styles, a page title and more!
Keep in mind, this process will work similar for the ajax version of the colorbox, but if you go the route of the ajax method, you will have to write the printable div and print iframe and print javascript directly to that external file.
Theoretically, anything inside the printable region div (in this example: pricingPrintArea) will print, so as-long-as you wrap that around whatever you want to print, it will do so.
Important tip: Printers all read a Web page differently so try not to rely too much on inline styles and pixel dimensions for your printable version. That is why it is a good idea to create a stylesheet specifically for the printable page.
Hopefully that answers your question. (btw, you should be able to get this method to work with the ajax method of colorbox, but I haven't tested it).

Resources