Image from canvas is not saved correctly - javascript

Good day to all users!
I have a problem that my screenshots rendered on canvas are not saved correctly.
Displaying screenshot on canvas using js
function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
if(pasteEvent.clipboardData == false){
if(typeof(callback) == "function"){
callback(undefined);
}
};
var items = pasteEvent.clipboardData.items;
if(items == undefined){
if(typeof(callback) == "function"){
callback(undefined);
}
};
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") == -1) continue;
var blob = items[i].getAsFile();
if(typeof(callback) == "function"){
callback(blob);
}
}
}
window.addEventListener("paste", function(e){
retrieveImageFromClipboardAsBlob(e, function(imageBlob){
if(imageBlob){
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function(){
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(img, 0, 0);
};
var URLObj = window.URL || window.webkitURL;
img.src = URLObj.createObjectURL(imageBlob);
}
});
var cnv = document.getElementById("mycanvas");
var sendCanvas = function (cnv) {
var imgs = cnv.toDataURL('image/png').replace('data:image/png;base64,','');
var sender = new XMLHttpRequest();
sender.open('POST', '/temp.php', true);
sender.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
sender.onreadystatechange = function () {
if (sender.readyState == 4) {}
};
sender.send('imgs='+imgs);
};
sendCanvas(cnv);
}, false);
First, the screenshot is drawn on canvas and then sent to the php handler.
My html form has:
<canvas id="mycanvas">
<?php
$imgs = str_replace(' ', '+', $_POST['imgs']);
$imgs = base64_decode($imgs);
$shootname = "screenshot".rand().".png";
$screendir = "/mnt/ElmaFiles/".$shootname;
file_put_contents($screendir, $imgs);
$screennames .= $shootname.",";
?>
<p><input type="submit" name="submit1" class="btn success"></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"</script>
<script src="/script11.js"></script>
In my understanding, files should be saved to the specified folder when I press ctrl + v. But it doesn't really work like that.
For example, I transfer 3 screenshots, but 5 screenshots are saved in my folder:
Please help me understand where is my mistake?
Thank you very much in advance!
I forgot to add: when 5 screenshots were saved, only the third and fourth could be opened from them, and the rest wrote an error like "incorrect format"

I did a little rewrite of the above which I hope will help solve some of the issues you were having.
The PHP that saves the image to disk should be explicitly targeted so that trying to call $_POST['imgs'] for a regular GET request will not cause issue. For sending the binary data to the server rather than XMLHttpRequest instead use fetch ~ a considerably more powerful api.
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['imgs'] ) ){
ob_clean();
$decoded=base64_decode( $_POST['imgs'] );
#edit directory to suit. This is a sub-folder to where the script is currently running.
$dir=sprintf('%s/images/tmp',__DIR__);
$filename=sprintf('screenshot%s.png', rand() );
$targetfile=sprintf('%s%s%s', realpath($dir), DIRECTORY_SEPARATOR, $filename );
file_put_contents( $targetfile, $decoded );
exit( $filename );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
function getBlob(evt,callback){
if( evt.clipboardData == false || evt.clipboardData.items=='undefined' ){
return false;
};
let items = evt.clipboardData.items;
for( let i=0; i < items.length; i++){
let item=items[i];
if( ~item.type.indexOf('image') )callback( item.getAsFile() );
}
}
window.addEventListener('paste', function(e){
let canvas = document.querySelector('canvas');
let ctxt = canvas.getContext('2d');
const callback=function( blob ){
if( blob ){
let img = new Image();
img.onload = function(){
canvas.width=this.width;
canvas.height=this.height;
ctxt.drawImage( img, 0, 0 );
};
img.src = URL.createObjectURL(blob);
return true;
}
return false;
};
getBlob( e, callback );
let fd=new FormData();
fd.append('imgs', canvas.toDataURL('image/png').replace('data:image/png;base64,',''));
fetch( location.href,{ method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
console.info('Screenshot %s saved',text )
})
});
});
</script>
</head>
<body>
<canvas></canvas>
</body>
</html>

Related

ReferenceError: PDFJS is not defined Asp.net

I'm trying to display a pdf using canvas and PDF.JS Stable v.2.2.228 but when I execute my webform it shows this error in the console: ReferenceError: PDFJS is not defined.
I read something about the global PDFJS object being removed but I can't find the correct syntax [Kinda new in JS]. Any suggestion is very appreciated
I was following this example in case is needed : https://usefulangle.com/post/20/pdfjs-tutorial-1-preview-pdf-during-upload-wih-next-prev-buttons
Js code:
function showPDF(pdf_url) {
PDFJS.getDocument({ url: pdf_url }).then(function (pdf_doc) {
__PDF_DOC = pdf_doc;
__TOTAL_PAGES = __PDF_DOC.numPages;
// Show the first page
showPage(1);
}).catch(function (error) {
// If error re-show the upload button
alert(error.message);
});;
}
function showPage(page_no) {
__PAGE_RENDERING_IN_PROGRESS = 1;
__CURRENT_PAGE = page_no;
__PDF_DOC.getPage(page_no).then(function (page) {
// As the canvas is of a fixed width we need to set the scale of the viewport accordingly
var scale_required = __CANVAS.width / page.getViewport(1).width;
// Get viewport of the page at required scale
var viewport = page.getViewport(scale_required);
// Set canvas height
__CANVAS.height = viewport.height;
var renderContext = {
canvasContext: __CANVAS_CTX,
viewport: viewport
};
page.render(renderContext).then(function () {
__PAGE_RENDERING_IN_PROGRESS = 0;
// Show the canvas and hide the page loader
$("#pdf-canvas").show();
});
});
}
function ValidateFileUpload() {
var fuData = document.getElementById('FileUpload1');
var FileUploadPath = fuData.value;
//To check if user upload any file
if (FileUploadPath == '') {
alert("Por favor subir un archivo");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "png" || Extension == "jpeg" || Extension == "jpg" || Extension == "gif" || Extension == "jfif") {
// To Display
if (fuData.files && fuData.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ImgPreview').attr('src', e.target.result);
//document.getElementById('ImgPreview').files[0].name;
var nombre= document.getElementById('ImgPreview').files[0].name;
document.querySelector('#LblFileupload').innerText = nombre;
}
reader.readAsDataURL(fuData.files[0]);
}
}
else if (Extension == "pdf") {
var __PDF_DOC,
__CURRENT_PAGE,
__TOTAL_PAGES,
__PAGE_RENDERING_IN_PROGRESS = 0,
__CANVAS = $('#pdf-canvas').get(0),
__CANVAS_CTX = __CANVAS.getContext('2d');
showPDF(URL.createObjectURL($("#FileUpload1").get(0).files[0]));
}
//The file upload is NOT an image
else {
alert("Solo se aceptan archivos en formato .JPG - .PNG - .JPEG - .GIF - .JFIF");
}
}
}
HTML :
<asp:FileUpload ID="FileUpload1" runat="server" accept="image/*" onchange="return ValidateFileUpload()" Visible="true" />
<asp:Image ID="ImgPreview" runat="server" Height="600px" Width="500px" />
<canvas id="pdf-canvas" width="400"> </canvas>
You should change PDFJS to pdfjsLib. Also you should try adding the lines var __CANVAS = $('#pdf-canvas').get(0); and var __CANVAS_CTX = __CANVAS.getContext('2d'); under __CURRENT_PAGE = page_no; in that function because you're not initializing those variables before you try to call and use them. Also you need to add var in front of the other two items you're using in that function at the top.
So it should look like:
pdfjsLib.getDocument(URL.createObjectURL($("#FileUpload1").get(0).files[0])).then(doc => {
console.log("This file has " + doc._pdfInfo.numPages + "pages");
doc.getPage(1).then(page => {
var myCanvas = document.getElementById('pdf-canvas');
var context = myCanvas.getContext('2d');
var viewport = page.getViewport(1);
myCanvas.width = viewport.width;
myCanvas.height = viewport.height;
page.render({
canvasContext: context,
viewport : viewport
}
);
});
});

PDF.js get images of one page and display them as HTML

according to this: [Extract images from PDF file with JavaScript
I tried to filter the JPEG images from PDF. It works in the way, that I get the name of the images of one page in an array.
What I want to do: Display the images next to the PDF as HTML . The solution mentioned above doesn't work, I do not know, how to get the image itself and not just the name.
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript">
PDFJS.workerSrc = "/path/to/pdf.worker.js";
</script>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas" style="width: 500px;"></canvas>
<div id="images"></div>
<script type="text/javascript">
PDFJS.workerSrc = "pdf.worker.js";
</script>
<script src="js.js"></script>
js.js:
// URL of PDF document
var url = "test/pdf_one.pdf";
var pageNum = 11;
var pageCount = 0;
loadPage(pageNum);
function loadPage(number){
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
pageCount = pdf.numPages;
document.getElementById("page_num").innerHTML = "" + pageNum;
document.getElementById("page_count").innerHTML = "" + pageCount;
return pdf.getPage(number);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
getImages(page);
});
}
function getImages(page){
var test = [];
page.getOperatorList().then(function (ops) {
for (var i=0; i < ops.fnArray.length; i++) {
if (ops.fnArray[i] == PDFJS.OPS.paintJpegXObject) {
console.log(ops.argsArray[i][0]);
document.getElementById("images").innerHTML = "<img src='"+ops.argsArray[i][0]+".jpg'>";
test.push(ops.argsArray[i][0])
}
}
});
console.log(test);
if(pageNum === 13){
console.log("IMAGES");
console.log(test[0]);
document.getElementById("images").innerHTML = "<img src='"+test[0]+".jpg'>";
}
}
document.getElementById('prev').addEventListener('click', onPrevPage);
document.getElementById('next').addEventListener('click', onNextPage);
function onNextPage() {
if (pageNum >= pageCount) {
return;
}
pageNum++;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}

capture whole div with svg in javascript

I want to capture whole div as image and save on local for proof.I have searched and read many articles about svg to image or div to image.
I have tried some js library for this.But when i try to capture image from div then some captures only div content and some captures only svg content.
s.jpg , a.jpg
html2canvas(contentDiv, {
onrendered: function(can) {
dirty.appendChild(can);
}
});
// first convert your svg to png
exportInlineSVG(svg, function(data, canvas) {
svg.parentNode.replaceChild(canvas, svg);
// then call html2canvas
html2canvas(contentDiv, {
onrendered: function(can) {
can.id = 'canvas';
clean.appendChild(can);
}
});
})
function exportInlineSVG(svg, receiver, params, quality) {
if (!svg || !svg.nodeName || svg.nodeName !== 'svg') {
console.error('Wrong arguments : should be \n exportSVG(SVGElement, function([dataURL],[canvasElement]) || IMGElement || CanvasElement [, String_toDataURL_Params, Float_Params_quality])')
return;
}
var xlinkNS = "http://www.w3.org/1999/xlink";
var clone;
// This will convert an external image to a dataURL
var toDataURL = function(image) {
var img = new Image();
// CORS workaround, this won't work in IE<11
// If you are sure you don't need it, remove the next line and the double onerror handler
// First try with crossorigin set, it should fire an error if not needed
img.crossOrigin = 'Anonymous';
img.onload = function() {
// we should now be able to draw it without tainting the canvas
var canvas = document.createElement('canvas');
var bbox = image.getBBox();
canvas.width = bbox.width;
canvas.height = bbox.height;
// draw the loaded image
canvas.getContext('2d').drawImage(this, 0, 0, bbox.width, bbox.height);
// set our original <image>'s href attribute to the dataURL of our canvas
image.setAttributeNS(xlinkNS, 'href', canvas.toDataURL());
// that was the last one
if (++encoded === total) exportDoc()
}
// No CORS set in the response
img.onerror = function() {
// save the src
var oldSrc = this.src;
// there is an other problem
this.onerror = function() {
console.warn('failed to load an image at : ', this.src);
if (--total === encoded && encoded > 0) exportDoc();
}
// remove the crossorigin attribute
this.removeAttribute('crossorigin');
// retry
this.src = '';
this.src = oldSrc;
}
// load our external image into our img
img.src = image.getAttributeNS(xlinkNS, 'href');
}
// The final function that will export our svgNode to our receiver
var exportDoc = function() {
// check if our svgNode has width and height properties set to absolute values
// otherwise, canvas won't be able to draw it
var bbox = svg.getBBox();
// avoid modifying the original one
clone = svg.cloneNode(true);
if (svg.width.baseVal.unitType !== 1) clone.setAttribute('width', bbox.width);
if (svg.height.baseVal.unitType !== 1) clone.setAttribute('height', bbox.height);
parseStyles();
// serialize our node
var svgData = (new XMLSerializer()).serializeToString(clone);
// remember to encode special chars
var svgURL = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgData);
var svgImg = new Image();
svgImg.onload = function() {
// if we set a canvas as receiver, then use it
// otherwise create a new one
var canvas = (receiver && receiver.nodeName === 'CANVAS') ? receiver : document.createElement('canvas');
// IE11 doesn't set a width on svg images...
canvas.width = this.width || bbox.width;
canvas.height = this.height || bbox.height;
canvas.getContext('2d').drawImage(this, 0, 0, canvas.width, canvas.height);
// try to catch IE
try {
// if we set an <img> as receiver
if (receiver.nodeName === 'IMG') {
// make the img looks like the svg
receiver.setAttribute('style', getSVGStyles(receiver));
receiver.src = canvas.toDataURL(params, quality);
} else {
// make the canvas looks like the canvas
canvas.setAttribute('style', getSVGStyles(canvas));
// a container element
if (receiver.appendChild && receiver !== canvas)
receiver.appendChild(canvas);
// if we set a function
else if (typeof receiver === 'function')
receiver(canvas.toDataURL(params, quality), canvas);
}
} catch (ie) {
console.warn("Your ~browser~ has tainted the canvas.\n The canvas is returned");
if (receiver.nodeName === 'IMG') receiver.parentNode.replaceChild(canvas, receiver);
else receiver(null, canvas);
}
}
svgImg.onerror = function(e) {
if (svg._cleanedNS) {
console.error("Couldn't export svg, please check that the svgElement passed is a valid svg document.");
return;
}
// Some non-standard NameSpaces can cause this issues
// This will remove them all
function cleanNS(el) {
var attr = el.attributes;
for (var i = 0; i < attr.length; i++) {
if (attr[i].name.indexOf(':') > -1) el.removeAttribute(attr[i].name)
}
}
cleanNS(svg);
for (var i = 0; i < svg.children.length; i++)
cleanNS(svg.children[i]);
svg._cleanedNS = true;
// retry the export
exportDoc();
}
svgImg.src = svgURL;
}
// ToDo : find a way to get only usefull rules
var parseStyles = function() {
var styleS = [],i;
// transform the live StyleSheetList to an array to avoid endless loop
for (i = 0; i < document.styleSheets.length; i++)
styleS.push(document.styleSheets[i]);
// Do we have a `<defs>` element already ?
var defs = clone.querySelector('defs') || document.createElementNS('http://www.w3.org/2000/svg', 'defs');
if (!defs.parentNode)
clone.insertBefore(defs, clone.firstElementChild);
// iterate through all document's stylesheets
for (i = 0; i < styleS.length; i++) {
var style = document.createElement('style');
var rules = styleS[i].cssRules,
l = rules.length;
for (var j = 0; j < l; j++)
style.innerHTML += rules[j].cssText + '\n';
defs.appendChild(style);
}
// small hack to avoid border and margins being applied inside the <img>
var s = clone.style;
s.border = s.padding = s.margin = 0;
s.transform = 'initial';
}
var getSVGStyles = function(node) {
var dest = node.cloneNode(true);
svg.parentNode.insertBefore(dest, svg);
var dest_comp = getComputedStyle(dest);
var svg_comp = getComputedStyle(svg);
var mods = "";
for (var i = 0; i < svg_comp.length; i++) {
if (svg_comp[svg_comp[i]] !== dest_comp[svg_comp[i]])
mods += svg_comp[i] + ':' + svg_comp[svg_comp[i]] + ';';
}
svg.parentNode.removeChild(dest);
return mods;
}
var images = svg.querySelectorAll('image'),
total = images.length,
encoded = 0;
// Loop through all our <images> elements
for (var i = 0; i < images.length; i++) {
// check if the image is external
if (images[i].getAttributeNS(xlinkNS, 'href').indexOf('data:image') < 0)
toDataURL(images[i]);
// else increment our counter
else if (++encoded === total) exportDoc()
}
// if there were no <image> element
if (total === 0) exportDoc();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="contentDiv" style="width: 50%;">
<img class="" src="s.jpg" width="75%">
<svg xmlns="http://www.w3.org/2000/svg" id="svg" height="100%">
<defs>
<clipPath id="my-path">
<text id="texty" style="font-weight:bold;" x="60" y="300" font-size="60">test</text>
</clipPath>
</defs>
<image xlink:href="a.jpg" clip-path="url(#my-path)" width="100%" height="100%" id="filler" preserveAspectRatio="none"></image>
</svg>
</div>
<div id="clean">clean:<br></div>
<div id="dirty">dirty :<br></div>
<style type="text/css">
svg {
position: relative;
top: -531px;
left: 120px;
}
</style>
I have attached three images. s.jpg image is my main image which is inside in main div. It is main image where user can write their name with texture color. To write text i have used svg inside main div and for texture i have used a.jpg as hidden image.
I used html2canvas js library to convert div into image but i did not get my desired output. Please help me to find out solution for this problem. Thanx in advance
Try this, very easy to use and works everytime :
Dom-To-Image
you can use saveSvgAsPng.js where you have to pass the svg element id along with file name to the image
in my case
saveSvgAsPng(document.getElementById('canvassvg'), "structure.png");
which stores the image in your temp or browser downloads location
(OR)
if you want to store it on server
convert the innerhtml content of of your main tag , i.e., from svg to /svg to base64 and use the base64 to image converter in the backend
var svgData = new XMLSerializer().serializeToString( svgobj );
var canvas = document.createElement( "canvas" );
var ctx = canvas.getContext( "2d" );
var img = document.createElement( "img" );
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
})));
svgData= btoa(encodeURIComponent(svgData).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
img.setAttribute( "src", "data:image/svg+xml;base64," + svgData );
var canvasd='';
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage( img, 0, 0 );
canvasd = canvas.toDataURL( "image/svg+xml" );
-base64 data is in canvasd
-ajax call to store to backend
};
return;

In an HTML/JavaScript file, how can I select a data file to include?

I have written a graphing program, but each time it runs it should prompt the user for a data file to plot.
Here is a very simplified program that has the data file (Data.js) hard coded in line 7:
<!DOCTYPE html>
<html>
<head>
<title>Warm-up</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script/>
<script src="./Data.js"></script>
<script>
function drawHorizontalLine(c, startX, startY, endX, endY) {
c.lineWidth = 3;
c.strokeStyle = '#888';
c.beginPath();
c.moveTo(startX, startY);
c.lineTo(endX, endY);
c.stroke();
}
$(document).ready(function() {
// Set the canvas width according to the length of time of the recording
var myCanvas = document.getElementById("graph");
var resultOfCalculation = 100;
myCanvas.width += resultOfCalculation;
graphWidened = $('#graph');
var graphCanvas = graphWidened[0].getContext('2d');
drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
});
</script/>
</head>
<body>
<canvas id="graph" width="600" height="450">
</body>
</html>
... where Data.js contains:
var endWidth = 200;
var endHeight = 150;
But I want to select the data file, something like this, perhaps:
<input type="file" id="sourcedFile" />
<p id="chosenFile" ></p>
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
document.getElementById("chosenFile").innerHTML = f.name;
} else {
alert("Failed to load file");
}
}
document.getElementById('sourcedFile').addEventListener('change', readSingleFile, false);
</script>
But I am having difficulty fitting the two pieces together in one file.
Obviously it should first request the data file and then draw the graph using the file name stored in the "chosenFile" variable.
I am new to HTML and JavaScript.
Thanks.
--- Edit ---
Thanks for your response, #TheGr8_Nik. I incorporated it in this file:
<!DOCTYPE html>
<html>
<head>
<title>Warm-up</title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<input type="file" id="sourcedFile" />
<p id="makeButtonGoAboveCanvas" ></p>
<script type="text/javascript">
var script;
//
// This function is called when sourcedFile changes as a result of user selection.
// It inserts the code lines (actually graph data) contained in sourceFile into this location.
//
// Selected files must be in the same directory as this file. (Why??)
// When running on a local computer the file selection only works in Firefox browser.
//
function insertDataFromSelectedFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (!f) {
alert("Failed to load file");
}
else {
script,
script_id = 'loaded_script',
//file_name = "./Data.js";
//file_name = "http://127.0.0.1:8887/Data.js";
//file_name = this.value.replace("C:\\fakepath\\", "http://127.0.0.1:8887/");
//file_name = this.value.replace("C:\\fakepath\\", "");
file_name = f.name;
script = document.createElement('script');
script.id = script_id; // assign an id so you can delete it after use
delete(endWidth); // To test if sourcing worked
script.src = file_name; // set the url to load
$('head').append( $(script) ); // append the new script in the header
if (typeof endWidth == 'undefined') {
alert ("endWidth is undefined. The selected file was not read or did not define endWidth");
}
else {
drawGraph();
}
$('#'+ script_id ).remove(); // remove the last loaded script - Seems to be unnecessary
}
}
function drawHorizontalLine(c, startX, startY, endX, endY) {
c.lineWidth = 3;
c.strokeStyle = '#888';
c.beginPath();
c.moveTo(startX, startY);
c.lineTo(endX, endY);
c.stroke();
}
function drawGraph() {
// Draw the graph
var myCanvas = document.getElementById("graph");
var resultOfCalculation = 100;
myCanvas.width += resultOfCalculation;
graphWidened = $('#graph');
var graphCanvas = graphWidened[0].getContext('2d');
drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
//drawHorizontalLine(graphCanvas, 10, 20, 400, 80);
}
document.getElementById('sourcedFile').addEventListener('change', insertDataFromSelectedFile, false);
</script>
</head>
<body>
<canvas id="graph" width="600" height="450">
</body>
</html>
I ran this on a local Windows machine with Chrome browser. Chrome caused huge problems by changing the file path to C:\fakepath\ and by complaining about "Cross origin requests are only supported for protocol schemes: http, .....". Changing to Firefox fixed those.
To get the script to work I deleted this line and its closing brace because the onload event didn't seem to be happening: script.onload = function () {
You can use js to inject a script tag in your html:
$( function () {
$('#sourcedFile').on( 'change', function () {
var script,
script_id = 'loaded_script',
file_name = this.value;
// check if the name is not empty
if ( file_name !== '' ) {
// creates the script element
script = document.createElement( 'script' );
// assign an id so you can delete id the next time
script.id = script_id;
// set the url to load
script.src = file_name;
// when the script is loaded executes your code
script.onload = function () {
var myCanvas = document.getElementById("graph");
var resultOfCalculation = 100;
myCanvas.width += resultOfCalculation;
graphWidened = $('#graph');
var graphCanvas = graphWidened[0].getContext('2d');
drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
};
// remove the last loaded script
$('#'+ script_id ).remove();
// append the new script in the header
$('head').append( $(script) );
}
});
});

Export Canvas content to PDF

I am working on something using HTML5 Canvas.
It's all working great, except right now, I can export the canvas content to PNG using Canvas2image. But I would like to export it to PDF. I've made some research and I'm pretty sure it's possible...but I can't seem to understand what I need to change in my code to make it work. I've read about a plugin called pdf.js...but I can't figure out how to implent it in my code.
First part :
function showDownloadText() {
document.getElementById("buttoncontainer").style.display = "none";
document.getElementById("textdownload").style.display = "block";
}
function hideDownloadText() {
document.getElementById("buttoncontainer").style.display = "block";
document.getElementById("textdownload").style.display = "none";
}
function convertCanvas(strType) {
if (strType == "PNG")
var oImg = Canvas2Image.saveAsPNG(oCanvas, true);
if (strType == "BMP")
var oImg = Canvas2Image.saveAsBMP(oCanvas, true);
if (strType == "JPEG")
var oImg = Canvas2Image.saveAsJPEG(oCanvas, true);
if (!oImg) {
alert("Sorry, this browser is not capable of saving " + strType + " files!");
return false;
}
oImg.id = "canvasimage";
oImg.style.border = oCanvas.style.border;
oCanvas.parentNode.replaceChild(oImg, oCanvas);
showDownloadText();
}
And the JS to that saves the image :
document.getElementById("convertpngbtn").onclick = function() {
convertCanvas("PNG");
}
document.getElementById("resetbtn").onclick = function() {
var oImg = document.getElementById("canvasimage");
oImg.parentNode.replaceChild(oCanvas, oImg);
hideDownloadText();
}
}
You need to use 2 plugins for this:
1) jsPDF
2) canvas-toBlob.js
Then add this piece of code to generate light weight PDF:
canvas.toBlob(function (blob) {
var url = window.URL || window.webkitURL;
var imgSrc = url.createObjectURL(blob);
var img = new Image();
img.src = imgSrc;
img.onload = function () {
var pdf = new jsPDF('p', 'px', [img.height, img.width]);
pdf.addImage(img, 0, 0, img.width, img.height);
pdf.save(fileName + '.pdf');
};
});
Look at this links:
http://www.codeproject.com/Questions/385045/export-html5-webpage-including-canvas-to-pdf
http://badassjs.com/post/708922912/pdf-js-create-pdfs-in-javascript
Most probably it will do the work you need
This jspdf is only useful in saving the file in the browser but we can't use that PDF generated to send to the server

Categories

Resources