PDF.JS only updates every other time - javascript

I'm trying to implement a "drag-to-pan" function for the pfd.js viewer.
However, this only works every other time, so that after panning around, I have to click the viewer again to make it re-render.
Here's the code:
var pdfScale = 1;
var activePdf;
var rotate = 0;
var addX = 0;
var addY = 0;
function renderPage(page) {
activePdf = page;
var canvas = document.getElementById('the-canvas');
var wrapperStyle = window.getComputedStyle(document.getElementsByClassName("canvas-wrapper")[0]);
var context = canvas.getContext('2d');
var viewport = page.getViewport(pdfScale, rotate);
canvas.height = parseInt(wrapperStyle.height);
canvas.width = parseInt(wrapperStyle.width);
viewport.viewBox[0] -= addX;
viewport.viewBox[2] -= addX;
viewport.viewBox[1] += addY;
viewport.viewBox[3] += addY;
addX = addY = 0;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
}
$(document).ready(function() {
var start = [0,0];
$('#the-canvas').mousedown(function(event) {
start[0] = event.screenX;
start[1] = event.screenY;
}).mouseup(function(event) {
console.log(event);
addX = event.screenX - start[0];
addY = event.screenY - start[1];
setTimeout(function() {
renderPage(activePdf);
}, 500);
});
var url = 'http://localhost/test.pdf';
// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
PDFJS.disableWorker = true;
// The workerSrc property shall be specified.
PDFJS.workerSrc = 'build/pdf.worker.js';
// Asynchronous download of PDF
var loadingTask = PDFJS.getDocument(url);
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
renderPage(page);
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
});
Even after adding the setTimeout, it still doesn't render correctly on the first time. How can I edit my logic to make it work?
Thanks!

Related

Prevent simultanous function calls when using pdf.js?

I use pdf.js to show pdf files, but the result is not good, please have a look at my code.
My codes are as follows.
var aaa = function (pdf, page_number) {
pdf.getPage(page_number).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = $('.pdf-view')[page_number-1];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
};
for (var i = 1;i < 51;i++) {
aaa(pdf, i);
if (i !== 50) {
var a = '<canvas data="{{ raw_path }}" class="pdf-view hide" style="margin-bottom:10px;"></canvas>';
$('#file-view #pdf').append(a);
}
}
There is a loop, then 50 functions (aaa) execute at the same time. The effect is disastrous, and my computer gets stuck. I want to excute a function right after the last function excuted very well.
Please help me improve it. Thank a lot. (Sorry, my English is disastrous as well.)
To avoid simultaneous run of single page load and render function aaa , you should move its call to callback of the page load - .then( part so it's called recursively. And then call aaa function only once with page_number = 1.
//define page render function
var aaa = function (pdf, page_number) {
pdf.getPage(page_number).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = $('.pdf-view')[page_number-1];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
if (i < 50) {
//render first 50 pages but not all pages except #50
aaa(pdf, i);
i++;
}
});
};
//pre-generate 50 canvases
var docFragment = document.createDocumentFragment();
for (var i = 1;i < 51;i++) {
var c = document.createElement("canvas");
$(c).data({{ raw_path }});
$(c).addClass('pdf-view hide');
$(c).css('margin-bottom', '10px');
docfrag.appendChild(c);
}
$('#file-view #pdf').append(docfrag);
//call render
var i = 1;
aaa(pdf, i);

PDF.js - Printing multiple documents at once

I need to place multiple PDFs on a page determined by an AJAX response, and when all documents and pages have rendered, call window.print.
The pages (canvases) of each document are being added to a div with class 'pdfdoc' to keep the pages in order by document.
I'm new to Promises, and I'm having trouble determining when to call window.print because of the async nature. Sometimes it is being called before all the pages are available even though I'm checking for the last page of the last document in the render promise before calling it. Below is the code:
// Called on each iteration of coredatalist
var getDoc = function(count) {
PDFJS.getDocument(srcUrl).then(function(pdf) {
var currentPage = 1;
$('<div class="pdfdoc" id="doc' + count + '"></div>').appendTo('body');
getPage(pdf, currentPage, count);
});
};
// Called for each page in PDF
var getPage = function(pdf, currentPage, count) {
pdf.getPage(currentPage).then(function(page) {
var scale = 2,
viewport = page.getViewport(scale),
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
renderContext = {
canvasContext: context,
viewport: viewport,
intent: 'print'
};
// Prepare canvas using PDF page dimensions
canvas.setAttribute('class', 'canvaspdf');
canvas.id = 'canvas' + currentPage;
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
page.render(renderContext).then(function(page) {
$('#doc' + count).append(canvas);
if (currentPage < pdf.numPages) {
currentPage++;
getPage(pdf, currentPage, count);
} else {
if (parseInt(count) === coredatalist.length - 1) {
window.print();
}
}
});
});
};
// Iterate through JSON object from AJAX request
for (var j in coredatalist) {
if (coredatalist.hasOwnProperty(j)) {
srcUrl = coredatalist[j].props.downloaduri;
getDoc(j);
}
}
Does anyone know how to call window.print after all documents AND pages are rendered?
For anyone interested, I fulfilled my requirements by wrapping PDFJS.getDocument() inside a function with a callback 'next':
loadPdf: function (pdfUrl, pdfindex, next) {
var self = this;
PDFJS.getDocument(pdfUrl).then(function (pdf) {
var currentPage = 1;
function getPage() {
pdf.getPage(currentPage).then(function (page) {
var scale = 2,
viewport = page.getViewport(scale),
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
renderContext = {
canvasContext: context,
viewport: viewport,
intent: 'print'
};
// Prepare canvas using PDF page dimensions
canvas.setAttribute('class', 'canvaspdf');
canvas.id = 'canvas' + currentPage + '-' + pdfindex;
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
page.render(renderContext).then(function (page) {
document.body.appendChild(canvas);
if (currentPage < pdf.numPages) {
currentPage++;
getPage();
} else {
next();
}
});
});
}
if (currentPage < pdf.numPages) {
getPage();
}
});
}
And then calling it within the callback:
var pdfUrls = [],
next = function () {
if (pdfUrls.length === 0) {
window.print();
} else {
self.loadPdf(pdfUrls.pop(), pdfUrls.length, next);
}
};
for (var j in coredatalist) {
if (coredatalist.hasOwnProperty(j)) {
pdfUrls.push('url');
}
}
next();

How to display whole PDF (not only one page) with PDF.JS?

I've created this demo:
http://polishwords.com.pl/dev/pdfjs/test.html
It displays one page. I would like to display all pages. One below another, or place some buttons to change page or even better load all standard controls of PDF.JS like in Firefox. How to acomplish this?
PDFJS has a member variable numPages, so you'd just iterate through them. BUT it's important to remember that getting a page in pdf.js is asynchronous, so the order wouldn't be guaranteed. So you'd need to chain them. You could do something along these lines:
var currPage = 1; //Pages are 1-based not 0-based
var numPages = 0;
var thePDF = null;
//This is where you start
PDFJS.getDocument(url).then(function(pdf) {
//Set PDFJS global object (so we can easily access in our page functions
thePDF = pdf;
//How many pages it has
numPages = pdf.numPages;
//Start with first page
pdf.getPage( 1 ).then( handlePages );
});
function handlePages(page)
{
//This gives us the page's dimensions at full scale
var viewport = page.getViewport( 1 );
//We'll create a canvas for each page to draw it on
var canvas = document.createElement( "canvas" );
canvas.style.display = "block";
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//Draw it on the canvas
page.render({canvasContext: context, viewport: viewport});
//Add it to the web page
document.body.appendChild( canvas );
//Move to next page
currPage++;
if ( thePDF !== null && currPage <= numPages )
{
thePDF.getPage( currPage ).then( handlePages );
}
}
Here's my take. Renders all pages in correct order and still works asynchronously.
<style>
#pdf-viewer {
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.1);
overflow: auto;
}
.pdf-page-canvas {
display: block;
margin: 5px auto;
border: 1px solid rgba(0, 0, 0, 0.2);
}
</style>
<script>
url = 'https://github.com/mozilla/pdf.js/blob/master/test/pdfs/tracemonkey.pdf';
var thePdf = null;
var scale = 1;
PDFJS.getDocument(url).promise.then(function(pdf) {
thePdf = pdf;
viewer = document.getElementById('pdf-viewer');
for(page = 1; page <= pdf.numPages; page++) {
canvas = document.createElement("canvas");
canvas.className = 'pdf-page-canvas';
viewer.appendChild(canvas);
renderPage(page, canvas);
}
});
function renderPage(pageNumber, canvas) {
thePdf.getPage(pageNumber).then(function(page) {
viewport = page.getViewport({ scale: scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({canvasContext: canvas.getContext('2d'), viewport: viewport});
});
}
</script>
<div id='pdf-viewer'></div>
The pdfjs-dist library contains parts for building PDF viewer. You can use PDFPageView to render all pages. Based on https://github.com/mozilla/pdf.js/blob/master/examples/components/pageviewer.html :
var url = "https://cdn.mozilla.net/pdfjs/tracemonkey.pdf";
var container = document.getElementById('container');
// Load document
PDFJS.getDocument(url).then(function (doc) {
var promise = Promise.resolve();
for (var i = 0; i < doc.numPages; i++) {
// One-by-one load pages
promise = promise.then(function (id) {
return doc.getPage(id + 1).then(function (pdfPage) {
// Add div with page view.
var SCALE = 1.0;
var pdfPageView = new PDFJS.PDFPageView({
container: container,
id: id,
scale: SCALE,
defaultViewport: pdfPage.getViewport(SCALE),
// We can enable text/annotations layers, if needed
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
annotationLayerFactory: new PDFJS.DefaultAnnotationLayerFactory()
});
// Associates the actual page with the view, and drawing it
pdfPageView.setPdfPage(pdfPage);
return pdfPageView.draw();
});
}.bind(null, i));
}
return promise;
});
#container > *:not(:first-child) {
border-top: solid 1px black;
}
<link href="https://npmcdn.com/pdfjs-dist/web/pdf_viewer.css" rel="stylesheet"/>
<script src="https://npmcdn.com/pdfjs-dist/web/compatibility.js"></script>
<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>
<script src="https://npmcdn.com/pdfjs-dist/web/pdf_viewer.js"></script>
<div id="container" class="pdfViewer singlePageView"></div>
The accepted answer is not working anymore (in 2021), due to the API change for var viewport = page.getViewport( 1 ); to var viewport = page.getViewport({scale: scale});, you can try the full working html as below, just copy the content below to a html file, and open it:
<html>
<head>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<head>
<body>
</body>
<script>
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
var currPage = 1; //Pages are 1-based not 0-based
var numPages = 0;
var thePDF = null;
//This is where you start
pdfjsLib.getDocument(url).promise.then(function(pdf) {
//Set PDFJS global object (so we can easily access in our page functions
thePDF = pdf;
//How many pages it has
numPages = pdf.numPages;
//Start with first page
pdf.getPage( 1 ).then( handlePages );
});
function handlePages(page)
{
//This gives us the page's dimensions at full scale
var viewport = page.getViewport( {scale: 1.5} );
//We'll create a canvas for each page to draw it on
var canvas = document.createElement( "canvas" );
canvas.style.display = "block";
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//Draw it on the canvas
page.render({canvasContext: context, viewport: viewport});
//Add it to the web page
document.body.appendChild( canvas );
var line = document.createElement("hr");
document.body.appendChild( line );
//Move to next page
currPage++;
if ( thePDF !== null && currPage <= numPages )
{
thePDF.getPage( currPage ).then( handlePages );
}
}
</script>
</html>
The following answer is a partial answer targeting anyone trying to get a PDF.js to display a whole PDF in 2019, as the api has changed significantly. This was of course the OP's primary concern. inspiration sample code
Please take note of the following:
extra libs are being used -- Lodash (for range() function) and polyfills (for promises)....
Bootstrap is being used
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div id="wrapper">
</div>
</div>
</div>
<style>
body {
background-color: #808080;
/* margin: 0; padding: 0; */
}
</style>
<link href="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.1.266/pdf_viewer.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.1.266/pdf.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.1.266/pdf_viewer.js"></script>
<script src="//cdn.polyfill.io/v2/polyfill.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<script>
$(document).ready(function () {
// startup
});
'use strict';
if (!pdfjsLib.getDocument || !pdfjsViewer.PDFViewer) {
alert("Please build the pdfjs-dist library using\n" +
" `gulp dist-install`");
}
var url = '//www.pdf995.com/samples/pdf.pdf';
pdfjsLib.GlobalWorkerOptions.workerSrc =
'//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.1.266/pdf.worker.js';
var loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(function(pdf) {
// please be aware this uses .range() function from lodash
var pagePromises = _.range(1, pdf.numPages).map(function(number) {
return pdf.getPage(number);
});
return Promise.all(pagePromises);
}).then(function(pages) {
var scale = 1.5;
var canvases = pages.forEach(function(page) {
var viewport = page.getViewport({ scale: scale, }); // Prepare canvas using PDF page dimensions
var canvas = document.createElement('canvas');
canvas.height = viewport.height;
canvas.width = viewport.width; // Render PDF page into canvas context
var canvasContext = canvas.getContext('2d');
var renderContext = {
canvasContext: canvasContext,
viewport: viewport
};
page.render(renderContext).promise.then(function() {
if (false)
return console.log('Page rendered');
});
document.getElementById('wrapper').appendChild(canvas);
});
},
function(error) {
return console.log('Error', error);
});
</script>
If you want to render all pages of pdf document in different canvases, all one by one synchronously this is kind of solution:
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Sample</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript" src="main.js">
</script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body id="body">
</body>
</html>
main.css
canvas {
display: block;
}
main.js
$(function() {
var filePath = "document.pdf";
function Num(num) {
var num = num;
return function () {
return num;
}
};
function renderPDF(url, canvasContainer, options) {
var options = options || {
scale: 1.5
},
func,
pdfDoc,
def = $.Deferred(),
promise = $.Deferred().resolve().promise(),
width,
height,
makeRunner = function(func, args) {
return function() {
return func.call(null, args);
};
};
function renderPage(num) {
var def = $.Deferred(),
currPageNum = new Num(num);
pdfDoc.getPage(currPageNum()).then(function(page) {
var viewport = page.getViewport(options.scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
if(currPageNum() === 1) {
height = viewport.height;
width = viewport.width;
}
canvas.height = height;
canvas.width = width;
canvasContainer.appendChild(canvas);
page.render(renderContext).then(function() {
def.resolve();
});
})
return def.promise();
}
function renderPages(data) {
pdfDoc = data;
var pagesCount = pdfDoc.numPages;
for (var i = 1; i <= pagesCount; i++) {
func = renderPage;
promise = promise.then(makeRunner(func, i));
}
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
};
var body = document.getElementById("body");
renderPDF(filePath, body);
});
First of all please be aware that doing this is really not a good idea; as explained in https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#allthepages
How to do it;
Use the viewer provided by mozilla;
https://mozilla.github.io/pdf.js/web/viewer.html
modify BaseViewer class, _getVisiblePages() method in viewer.js to
/* load all pages */
_getVisiblePages() {
let visible = [];
let currentPage = this._pages[this._currentPageNumber - 1];
for (let i=0; i<this.pagesCount; i++){
let aPage = this._pages[i];
visible.push({ id: aPage.id, view: aPage, });
}
return { first: currentPage, last: currentPage, views: visible, };
}
If you want to render all pages of pdf document in different canvases
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="pdf.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<h1>PDF.js 'Hello, world!' example</h1>
<div id="canvas_div"></div>
<body>
<script>
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = 'pdff.pdf';
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'worker.js';
var loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(function(pdf) {
var __TOTAL_PAGES = pdf.numPages;
// Fetch the first page
var pageNumber = 1;
for( let i=1; i<=__TOTAL_PAGES; i+=1){
var id ='the-canvas'+i;
$('#canvas_div').append("<div style='background-color:gray;text-align: center;padding:20px;' ><canvas calss='the-canvas' id='"+id+"'></canvas></div>");
var canvas = document.getElementById(id);
//var pageNumber = 1;
renderPage(canvas, pdf, pageNumber++, function pageRenderingComplete() {
if (pageNumber > pdf.numPages) {
return;
}
// Continue rendering of the next page
renderPage(canvas, pdf, pageNumber++, pageRenderingComplete);
});
}
});
function renderPage(canvas, pdf, pageNumber, callback) {
pdf.getPage(pageNumber).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport({scale: scale});
var pageDisplayWidth = viewport.width;
var pageDisplayHeight = viewport.height;
//var pageDivHolder = document.createElement();
// Prepare canvas using PDF page dimensions
//var canvas = document.createElement(id);
var context = canvas.getContext('2d');
canvas.width = pageDisplayWidth;
canvas.height = pageDisplayHeight;
// pageDivHolder.appendChild(canvas);
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext).promise.then(callback);
});
}
</script>
<html>
The accepted answer works perfectly for a single PDF. In my case there were multiple PDFs that I wanted to render all pages for in the same sequence of the array.
I adjusted the code so that the global variables are encapsulated in an object array as follows:
var docs = []; // Add this object array
var urls = []; // You would need an array of the URLs to start.
// Loop through each url. You will also need the index for later.
urls.forEach((url, ix) => {
//Get the document from the url.
PDFJS.getDocument(url).then(function(pdf) {
// Make new doc object and set the properties of the new document
var doc = {};
//Set PDFJS global object (so we can easily access in our page functions
doc.thePDF = pdf;
//How many pages it has
doc.numPages = pdf.numPages;
//Push the new document to the global object array
docs.push(doc);
//Start with first page -- pass through the index for the handlePages method
pdf.getPage( 1 ).then(page => handlePages(page, ix) );
});
});
function handlePages(page, ix)
{
//This gives us the page's dimensions at full scale
var viewport = page.getViewport( {scale: 1} );
//We'll create a canvas for each page to draw it on
var canvas = document.createElement( "canvas" );
canvas.style.display = "block";
var context = canvas.getContext('2d');
canvas.height = viewport.viewBox[3];
canvas.width = viewport.viewBox[2];
//Draw it on the canvas
page.render({canvasContext: context, viewport: viewport});
//Add it to an element based on the index so each document is added to its own element
document.getElementById('doc-' + ix).appendChild( canvas );
//Move to next page using the correct doc object from the docs object array
docs[ix].currPage++;
if ( docs[ix].thePDF !== null && docs[ix].currPage <= docs[ix].numPages )
{
console.log("Rendering page " + docs[ix].currPage + " of document #" + ix);
docs[ix].thePDF.getPage( docs[ix].currPage ).then(newPage => handlePages(newPage, ix) );
}
}
Because the entire operation is asynchronous, without a unique object for each document, global variables of thePDF, currPage and numPages will be overwritten when subsequent PDFs are rendered, resulting in random pages being skipped, documents entirely skipped or pages from one document being appended to the wrong document.
One last point is that if this is being done offline or without using ES6 modules, the PDFJS.getDocument(url).then() method should change to pdfjsLib.getDocument(url).promise.then().
Make it to be iterate every page how much you want.
const url = '/storage/documents/reports/AR-2020-CCBI IND.pdf';
pdfjsLib.GlobalWorkerOptions.workerSrc = '/vendor/pdfjs-dist-2.12.313/package/build/pdf.worker.js';
const loadingTask = pdfjsLib.getDocument({
url: url,
verbosity: 0
});
(async () => {
const pdf = await loadingTask.promise;
let numPages = await pdf.numPages;
if (numPages > 10) {
numPages = 10;
}
for (let i = 1; i <= numPages; i++) {
let page = await pdf.getPage(i);
let scale = 1.5;
let viewport = page.getViewport({ scale });
let outputScale = window.devicePixelRatio || 1;
let canvas = document.createElement('canvas');
let context = canvas.getContext("2d");
canvas.width = Math.floor(viewport.width * outputScale);
canvas.height = Math.floor(viewport.height * outputScale);
canvas.style.width = Math.floor(viewport.width) + "px";
canvas.style.height = Math.floor(viewport.height) + "px";
document.getElementById('canvas-column').appendChild(canvas);
let transform = outputScale !== 1
? [outputScale, 0, 0, outputScale, 0, 0]
: null;
let renderContext = {
canvasContext: context,
transform,
viewport
};
page.render(renderContext);
}
})();

How do i deal with data:img elements populating in my resources?

Notice the data:img images... I dont know how to remove them from memory and document.images does not contain them...
I am writing a Chrome Extension. Its somewhat of a hybrid screenshot app and basically when a user scrolls it takes the new part of the screen that the user has scrolled to and appends it on to a master screenshot of the entire site (yeah i have used googles screenshot app). My code works, but when I pass the img from the extension to the content script its storing the data:img sources into somewhere in memory where I cant access. I have tried document.images and tested to see if they may be populated within but with no luck.
Heres the code if you are interested.
page.js
var ovr = 0;
var run = (window==window.top)?1:0;
if(run&&ovr){
function obj(){
window.onload = function(){
obj.conversion = .5;
obj.screenShot();
obj.startRecordingScroll();
obj.showShot();
};
}
obj.showShot = function(){
obj.fullShot = document.createElement('canvas');
obj.fullShot.zIndex = -100;
obj.fullShot.style.position = 'fixed';
obj.fullShot.style.top = '70px';
obj.fullShot.style.right = '20px';
obj.fullShot.style.backgroundColor = '#999999';
obj.fullShot.width = window.innerWidth*obj.conversion;
obj.fullShot.height = document.height*obj.conversion;
document.body.appendChild(obj.fullShot);
obj.ctx = obj.fullShot.getContext('2d');
};
obj.startRecordingScroll = function(){
document.onscroll = function(){
obj.scroll();
};
};
obj.scroll = function(){
var pagxoff = window.pageXOffset;
var pagyoff = window.pageYOffset;
alert(document.images.length);
console.log("scroll");
obj.screenShot();
};
obj.displayScreenShot = function(img){
console.log('displayScreenShot');
var ycur = window.pageYOffset;
var yMaxCur = window.innerHeight+window.pageYOffset;
var distance = yMaxCur - obj.lastMaxYSeen;
distance = Math.abs(distance);
if(!obj.firstRunShot){
obj.lastMinYSeen = window.pageYOffset;
obj.lastMinXSeen = window.pageXOffset;
obj.lastMaxYSeen = (window.innerHeight+window.pageYOffset);
obj.lastMaxXSeen = (window.innerWidth+window.pageXOffset);
var shot = document.createElement('img');
shot.src = img;
console.log(img);
shot.onload = function(){
obj.ctx.drawImage(
shot,
0, // 0 right
0, // 0 down
window.innerWidth, // viewport width
window.innerHeight, // viewport height
0, // 0 right
0, // 0 down
window.innerWidth*obj.conversion,
window.innerHeight*obj.conversion
);
};
obj.firstRunShot = true;
return;
}
if(obj.firstRunShot){
if(ycur>obj.lastMinYSeen){
obj.lastMinYSeen = window.pageYOffset;
obj.lastMinXSeen = window.pageXOffset;
obj.lastMaxYSeen = (window.innerHeight+window.pageYOffset);
obj.lastMaxXSeen = (window.innerWidth+window.pageXOffset);
var xshot = document.createElement('img');
xshot.src = img;
xshot.onload = function(){
obj.ctx.drawImage(
xshot,
0,
window.innerHeight-distance,
window.innerWidth,
distance,
0,
(obj.lastMaxYSeen-distance)*obj.conversion,
window.innerWidth*obj.conversion,
(distance)*obj.conversion
);
};
return;
}
}
};
obj.screenShot = function(){
var port = chrome.extension.connect({
name: "screenshot"
});
port.postMessage({
request: "screenshot"
});
port.onMessage.addListener(function (msg) {
obj.displayScreenShot(msg);
});
console.log('screenShot');
};
var builder = new obj();
}
You can track resources being added and manipulate all contents of these resources using chrome.devtools.inspectedWindow API's, if you want to delete some resource modify DOM by deleting node(s).
document.images does contain the resources.
The Resources panel lets you inspect resources that are loaded in the inspected page, are you loading your image into inspected page to show up here?
If you are trying to store image to local disk using FILE API, remember they are sand-boxed and cannot be accessed by other means.
References
chrome.devtools.inspectedWindow
Resources Panel
File API
Content Scripts

Javascript News Scroller

see the news scroller on the top of this site
http://track.dc.gov/Agency/DH0
Any idea what library/functions this site uses to implment such a smooth scroller?
They have a very nicely formatted block of code you can study. Open your favorite JS debugger when you visit the site, wait for everything to get moving, and then press "Break All" or the equivalent in your debugger. You'll see something like the following:
Dashboard.UI.EndlessLine = function() {
var me = this;
me.jq = $(me);
me.classNames = { CONTAINER: "uiEndless", VIEW: "uiEndlessView", CANVAS: "uiEndlessCanvas", TILE: "uiEndlessTile" };
var canvas = null;
var view = null;
var tiles = null;
var x = 0;
var xx = 0;
var canvasWidth = 0;
var step = 1;
var delay = 40;
me.initialize = function(container, data, handler) {
required(container, "container");
required(data, "data");
required(handler, "handler");
container.addClass(me.classNames.CONTAINER);
view = newDiv(me.classNames.VIEW);
canvas = newDiv(me.classNames.CANVAS);
view.append(canvas);
container.append(view);
x = 0;
xx = 0;
canvasWidth = 0;
tiles = me.populateTiles(data, handler);
container.click(function() {
if (me.started()) me.stop(); else me.start();
});
};
me._resize = function(size) {
};
var moveId = 0;
me.start = function() {
me.stop();
me.tick();
}
me.stop = function() {
if (moveId > 0) clearTimeout(moveId);
moveId = 0;
}
me.started = function() {
return moveId > 0;
};
me.tick = function() {
var tile = tiles.current();
var width = tile.calculatedWidth;
if (x < width - step) {
x += step;
} else {
x = 0;
tile.css("left", canvasWidth + "px");
if (tiles.advance()) {
xx = 0;
canvasWidth = 0;
do {
current = tiles.current();
width = current.calculatedWidth;
current[0].style.left = canvasWidth + "px";
canvasWidth += width;
} while (!tiles.advance());
} else {
canvasWidth += width;
}
}
canvas[0].style.left = -(xx) + "px";
xx += step;
moveId = setTimeout(me.tick, delay);
}
me.populateTiles = function(data, handler) {
var tiles = new Dashboard.Core.List();
var viewWidth = view.contentWidth();
var maxHeight = 0;
each(data, function() {
var tile = newDiv(me.classNames.TILE);
handler.call(this, tile);
tile.css({ left: canvasWidth + "px", top: 0 });
canvas.append(tile);
var width = tile.outerWidth();
var height = tile.outerHeight();
if (maxHeight < height) maxHeight = height;
tile.calculatedWidth = width;
canvasWidth += width; // getting width may only be done after the element is attached to DOM
tiles.append(tile);
view.height(height);
});
return tiles.createCycle();
}
}
I'm impressed -- everything looks professional and nicely namespaced.
Update: If you want an explanation of how it works, focus on the tick method defined above. Glossing over all the details (cause I haven't really studied it myself), it calculates a step size, moves the message element to the left by the some amount, and schedules the next tick call for 40 milliseconds in the future.
jQuery enthusiast, Remy Sharp, has his own Marquee Plugin that you can implement pretty easily. You can gather deeper details of it on his blog or by visiting the demo page.
For Mootools users, there's Mooquee.
You can also view the actual code for this example online at http://track.dc.gov/Resource/Script/ - do a search for "uiEndless" to find the target-scripting.

Categories