javascript: Highlighting image areas / sections - javascript

I want to create a simple jsp / servlet code which should have the following:
1) Display an image having different sections. For example: a country map.
2) Allow the user to mark sections on this image using mouse drag. As the user keeps dragging the mouse, the area gets overlay-ed with some different color.
3) As the user moves the mouse, the x and y coordinates on the image should also get calculated. [This feature is however optional.]
The purpose of this application is to mark different 'zones' in an image, which will get saved in the database along with their x-y coordinates.
Can someone please suggest how to achieve this ? Is there any library / API available which could be helpful ?
Regards,

Here is a snippet to get you going. Replace the text setting of the div#server with code to send coordinates to your server. I'll leave the background image for canvas and other important stuff up to you.
var c = $("#map");
var ctx = c[0].getContext("2d");
var down = [0, 0];
var bound = c[0].getBoundingClientRect();
c.mousedown(function(e) {
down = [e.clientX - bound.left, e.clientY - bound.top];
});
c.mouseup(function(e) {
var rect = [
down[0],
down[1], ((e.clientX - bound.left) - down[0]), ((e.clientY - bound.top) - down[1])
];
ctx.fillStyle = "#bbbbbb";
ctx.fillRect(rect[0], rect[1], rect[2], rect[3]);
$("#server").text("Send: " + rect);
});
body {
background-color: lightblue;
}
#map {
background-color: white;
cursor: crosshair;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="map" width="256" height="256"></canvas>
<div id="server"></div>

Related

zoom into html canvas

I would like show a cutting of a canvas element in another canvas element. For explanation i have the following structure:
Canvas Element which gets filled it's background by an image. On top of this image i draw a arrow and a possible path. The background-image is really big, which means that i can not get that much Information from this big image. This is the reason for point two.
I would like to show a cutting of the canvas element 1. For example like the following image:
Currently i get the coordinate of the red arrow in canvas element 1, now i would like to do something like a cutting of this section with offset like in the image.
How could i solve something like this with JavaScript / JQuery. In summary i have two canvas elements. One of them is showing a big map with a red arrow which represents the current location (this works already), but now i wanna show a second canvas element with the zoom of this section where the red arrow is. Currently i am getting the coordinates, but no idea how i could "zoom" into an canvas element.
Like some of the current answers said, i provide some code:
My HTML Code, there is the mainCanvasMap, which has a Background Image and there is the zoomCanvas, which should display a section of the mainCanvasMap!
Here is a JavaScript snippet, which renders the red arrow on the map and should provide a zoom function (where the red-arrow is located) to the zoomCanvas Element.
var canvas = {}
canvas.canvas = null;
canvas.ctx = null;
canvas.scale = 0;
var zoomCanvas = {}
zoomCanvas.canvas = null;
zoomCanvas.ctx = null;
zoomCanvas.scale = 0;
$(document).ready(function () {
canvas.canvas = document.getElementById('mainCanvasMap');
canvas.ctx = canvas.canvas.getContext('2d');
zoomCanvas.canvas = document.getElementById('zoomCanvas');
zoomCanvas.ctx = zoomCanvas.canvas.getContext('2d');
setInterval(requestTheArrowPosition, 1000);
});
function requestTheArrowPosition() {
renderArrowOnMainCanvasElement();
renderZoomCanvas();
}
function renderArrowOnMainCanvasElement(){
//ADD ARROW TO MAP AND RENDER THEM
}
function renderZoomCanvas() {
//TRY TO ADD THE ZOOM FUNCTION, I WOULD LIKE TO COPY A SECTION OF THE MAINCANVASMAP
zoomCanvas.ctx.fillRect(0, 0, zoomCanvas.canvas.width, zoomCanvas.canvas.height);
zoomCanvas.ctx.drawImage(canvas.canvas, 50, 100, 200, 100, 0, 0, 400, 200);
zoomCanvas.canvas.style.top = 100 + 10 + "px"
zoomCanvas.canvas.style.left = 100 + 10 + "px"
zoomCanvas.canvas.style.display = "block";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!--MY MAIN CANVAS ELEMENT, WHICH HAS A BACKGROUND IMAGE AND WHERE THE ARROW IS RENDEREED-->
<canvas id="mainCanvasMap" style="width:100%; height:100%; background: url('https://image.jimcdn.com/app/cms/image/transf/dimension=624x10000:format=jpg/path/s7d1eecaa5cee1012/image/i4484f962de0bf3c2/version/1543751018/image.jpg') 0% 0% / 100% 100%;"></canvas>
<!-- MY ZOOM CANVAS ELEMENT, SHOULD SHOW A CUTTING OF THE MAINCANVASMAP -->
<canvas id="zoomCanvas" style="height:100%;width:100%"></canvas>
The code is only a pseudo-code, but it shows what i like to do.
Your code is using css for the canvas image, that not always looks the way we think...
I will recommend you to draw everything from scratch, here is a starting point:
canvas = document.getElementById('mainCanvasMap');
ctx = canvas.getContext('2d');
zoomCanvas = document.getElementById('zoomCanvas');
zoomCtx = zoomCanvas.getContext('2d');
var pos = {x:0, y:40}
image = document.getElementById('source');
image.onload = draw;
function draw() {
ctx.drawImage(image,0,0);
setInterval(drawZoom, 80);
}
function drawZoom() {
// simple animation on the x axis
x = Math.sin(pos.x++/10 % (Math.PI*2)) * 20 + 80
zoomCtx.drawImage(image, x, pos.y, 200, 100, 0, 0, 400, 200);
}
<canvas id="mainCanvasMap"></canvas>
<canvas id="zoomCanvas"></canvas>
<img id="source" src="https://image.jimcdn.com/app/cms/image/transf/dimension=624x10000:format=jpg/path/s7d1eecaa5cee1012/image/i4484f962de0bf3c2/version/1543751018/image.jpg" style="display:none">

How to scroll large texts in paperjs

I am using paper.js to create a (non-interactive) display. I have fixed area inside which I want to show some text. When the text is large, I want to clip the text so as to show only the part inside the fixed area is visible to the user. In addition, in that case, I want to scroll the text left-to-right repeatedly.
As far as I could read in the paperjs documentation, there is no strait forward way to achieve this (.
So, I am thinking of doing the following:
Determine if the text is larger than the container box. Could not find an easy way to do this. Thinking of having a simple heuristic function - which goes by the number of characters in the text.
Clip the text within the container box. I have not figured out yet but it appears possible.
Change the anchor point gradually to the left to create the scrolling effect. Again to determine how far to go, we would need the size of the text - but may need to depend on a heuristic function again.
May be the upcoming feature AreaText would make doing this easier. Please let me know if there is a better way to do this in the meantime. Thanks.
Please let me know if there are samples in plain canvas or in another js framework ...
If PaperJS works well for your app but you need scrolling text, you could make a hybrid app that uses both a PaperJS canvas and a native html5 canvas. The native html5 canvas could just do the scrolling text.
Since you ask for ideas...Here's an autoscrolling text script that I did a while back.
You're welcome to use the code as a starting point for your scrolling script. It word-wraps sentences into paragraphs and then displays them on an auto-scrolling html canvas.
When you need to display some text you could temporarily overlay your PaperJS canvas with this scrolling text html5 canvas and remove the html5 canvas when done displaying the text. Its would also be easy to give the user control of the scrolling using an html input-range control.
Example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var Paragraphs=( function(){
function Paragraphs(x,y,maxwidth,fontsize,fontface){
this.x=x;
this.y=y;
this.originalY=y;
this.maxwidth=maxwidth;
this.fontsize=fontsize;
this.fontface=fontface;
this.autoLineAdvance=true;
this.writeCount=0;
this.p=[];
this.nextTime=0;
this.duration=1000/60*1;
this.viewheight=150;
this.offsetY=0;
this.canvas=document.createElement('canvas');
this.ctx=this.canvas.getContext('2d');
this.totalHeight=0;
};
Paragraphs.prototype.addParagraph=function(text){ this.p.push(text); }
Paragraphs.prototype.autoscroll=function(viewportHeight){
this.viewheight=ch;
this.offsetY=ch;
requestAnimationFrame(this.animatescroll.bind(this));
};
Paragraphs.prototype.animatescroll=function(time){
var that=this;
if(this.offsetY>0){
requestAnimationFrame(that.animatescroll.bind(that));
}else{log('done');}
if(time<this.nextTime){return;}
this.nextTime=time+this.duration;
ctx.clearRect(0,0,cw,ch);
ctx.drawImage(this.canvas,this.x,this.offsetY);
this.offsetY-=0.50;
};
Paragraphs.prototype.lineAdvance=function(){this.y+=this.fontsize*1.286*1.5};
Paragraphs.prototype.drawOffCanvas=function(){
var y=0;
var lineCount=0;
var lineHeight = this.fontsize*1.286;
var lineAdvance=lineHeight*1.5;
this.canvas.width=this.maxwidth;
this.canvas.height=this.height();
this.ctx.textBaseline='top';
this.ctx.font = this.fontsize + "px " + this.fontface;
for(var i=0;i<this.p.length;i++){
var words=this.p[i].split(' ');
var line = '';
var space='';
for (var n=0; n<words.length; n++) {
var testLine = line + space + words[n];
space=' ';
if (this.ctx.measureText(testLine).width > this.maxwidth) {
this.ctx.fillText(line, 1, y);
line = words[n] + ' ';
y += lineHeight;
space='';
} else {
line = testLine;
}
}
this.ctx.fillText(line, 1,y);
y+=lineAdvance;
}
};
Paragraphs.prototype.height=function(){
ctx.save();
ctx.textBaseline='top';
ctx.font = this.fontsize + "px " + this.fontface;
var lineHeight = this.fontsize*1.286;
var writeCount=0;
var height=lineHeight*(this.p.length-1)*0.50;
var line,space;
for(var i=0;i<this.p.length;i++){
var words=this.p[i].split(' ');
line=space='';
if((writeCount++)>0){ height+=lineHeight; }
for (var n=0; n<words.length; n++) {
var testLine = line + space + words[n];
space=' ';
if (ctx.measureText(testLine).width > this.maxwidth) {
line = words[n] + ' ';
height+=lineHeight;
space='';
} else {
line = testLine;
}
}
}
height+=lineHeight;
ctx.restore();
this.totalHeight=height;
return(height);
}
return(Paragraphs);
})();
var d=new Paragraphs(35,20,200,14,'verdana');
d.addParagraph("I am using paper.js to create a (non-interactive) display. I have fixed area inside which I want to show some text. When the text is large, I want to clip the text so as to show only the part inside the fixed area is visible to the user. In addition, in that case, I want to scroll the text left-to-right repeatedly.");
d.addParagraph("Please let me know if there are samples in plain canvas or in another js framework ...");
d.drawOffCanvas();
d.autoscroll();
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<h4>Text scrolls in from the bottom<br>Be patient or click full page mode</h4>
<canvas id="canvas" width=300 height=300></canvas>

Error in JavaScript on Canvas(HTML5)- can't figure it out

I have JavaScript code in my site.
The code is using 2 identical photos-same size, same resolution - only different colors.
First photo is black and white photo - this is what the canvas presents.
Second photo is the same only with the original colors.
I have a button that triggers JS code - which generally removes a pixel from the black and white -and paints color pixel on the canvas. At first I used Math.random for the pixel locations.
And than I decided to use it by order. No matter where it starts or begging.. as long it will go
in this order (x,y)..(x+1,y).. until maximum x.. and than (x,y+1).. until maximum x.. and so on until all the black and white photo "transformed" into the colorful photo..
for some reason I just cant make it happen.. i tried a lot of techniques..
here is demo for global understanding:
demo is working sorry - they deactivated my free host :\ hope you still understand..
here is the original code- i just changed the last function : **removeDrawRandomPixel** ..it's just playing the function there and it should be fixed..
///////////////////////global variables///////////////////
var gray_url="bwcat.jpg"; //black and white image URI
var regular_url="cat.jpg"; //regular image URI
var n=100; //number of pixels changed per click
/////////////////////////////////////
document.addEventListener("DOMContentLoaded", function(){
var c=new EditableCanvas(document.getElementById('cnvs'));
grayScaleImage=new Image();
grayScaleImage.src=gray_url;
grayScaleImage.onload=function()
{
c.drawImage(this);
}
regularImage=new Image();
regularImage.src=regular_url;
regularImage.onload=function()
{
var p=getPixelArray(this);
btn.onclick=function(){
for(var i=1;i<=n&&p.length>0;i++){
removeDrawRandomPixel(p,c);
}
}
}
},false);
//create a Pixel object
function ImagePixel(x,y,r,g,b,a)
{
this.x=x;
this.y=y;
this.r=r;
this.g=g;
this.b=b;
this.a=a;
}
//object that allows custom methods
function EditableCanvas(canvas)
{
this.canvas=canvas;
this.context=canvas.getContext('2d');
this.width=canvas.width;
this.height=canvas.height;
this.pixelImage=this.context.createImageData(1,1);
//draw an entire picture and adjust the canvas for it
this.drawImage=function(image)
{
this.width=image.width;
this.height=image.height;
this.canvas.height=image.height;
this.canvas.width=image.width;
this.context.drawImage(image,0,0);
}
//draw a single pixel, ImagePixel pixel
this.drawPixel=function(pixel)
{
this.pixelImage.data[0]=pixel.r;
this.pixelImage.data[1]=pixel.g;
this.pixelImage.data[2]=pixel.b;
this.pixelImage.data[3]=pixel.a;
this.context.putImageData(this.pixelImage,pixel.x,pixel.y);//,pixel.x,pixel.y);
}
}
//the function returns an ordered array of Pixel pixels of the image at `src`.
function getPixelArray(img)
{
var pixelArray=[];
var cnvs=document.createElement('canvas');
cnvs.width=img.width;
cnvs.height=img.width;
var context=cnvs.getContext('2d');
context.drawImage(img,0,0);
var originalData = context.getImageData(0,0,img.width,img.height).data;
for(var i=0,pixelId=0,px;i<originalData.length;i+=4)
{
px=new ImagePixel(pixelId%img.width,Math.floor(pixelId/img.width),originalData[i],originalData[i+1],originalData[i+2],originalData[i+3]);
pixelArray.push(px);
pixelId++;
}
return pixelArray;
}
//the function remove a random pixel from pixelArray and draws it on editableCnvs
function removeDrawRandomPixel(pixelArray,editableCnvs)
{
var place=Math.floor(Math.random()*pixelArray.length);
var px=pixelArray.splice(place,1)[0];
editableCnvs.drawPixel(px);
}
html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas rules</title>
<script src="pixel.js"></script>
</head>
<body>
<canvas id="cnvs">
oh goddmamit no support
</canvas>
<button id="btn">click to convert</button>
</body>
</html>
I tried playing the last function.. because i know the answer is in the function,how to choose the pixels..
This is untested however this is what I would change the removeDrawRandomPixel function to. You are grabbing a random point in the array currently and passing it, so it could be starting on the blue component of one pixel and ending on the g component of another pixel.
//the function remove a random pixel from pixelArray and draws it on editableCnvs
function removeDrawRandomPixel(pixelArray,editableCnvs)
{
// width and height need to be the width and height of the canvas.
var width = canvas.width,
height = canvas.height,
x = Math.floor(Math.random()*width),
y = Math.floo(Math.random()*height);
var px = (y * width + x) * 4;
editableCnvs.drawPixel(px);
}

Drawing a timeline from div to div with canvas

I have the following div markup
<div data-x="-1000" data-y="-1500">
// content
</div>
<div data-x="0" data-y="-1500">
// content
</div>
And I have many of this divs with different data-x and data-y value depending on their position.
What I want to achieve here is to draw something like a timeline between the divs so div1 line to div2 line to div 3 etc,,
I want this to be done automatically So I am trying to make a loop for it but my javascript/jquery knowledge is not that good. Could someone point me in the good direction?
what I have now is
function drawTimeline() {
var divs = document.getElementsByTagName('div');
var canvas = document.getElementById('timeline');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
var prevCoord = {};
for (var i = -1; div = divs[++i]; ) {
if (div.dataset.x && div.dataset.y) {
var x = parseInt(div.dataset.x);
var y = parseInt(div.dataset.y);
if ({} !== prevCoord) {
ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="purple"; // Purple path
ctx.moveTo(prevCoord.x, prevCoord.y);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke()
}
prevCoord.x = x;
prevCoord.y = y;
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this.');
}
}
unfortunately the line is not correct its like a linear line and thats it.. can someone help me out with this?
You have the right idea, but your problem is that canvas does not draw at negative coordinates.
Therefore, you must map all your data-x and data-y into positive coordinates.
Here's a function that maps your negative values into positive values:
function mapRange(value, sourceLow, sourceHigh, mappedLow, mappedHigh) {
return mappedLow + (mappedHigh - mappedLow) * (value - sourceLow) / (sourceHigh - sourceLow);
}
So in your example to map a data-x value of -300 into an onscreen range of 0-1000 can do this:
var x = mapRange(-300, -1500,0, 0,1000); // The mapped x is 466.66.
You must reposition your divs to the mapped x,y coordinates which you can do with CSS.
An alternative is to use SVG which creates actual DOM elements that can be positioned at negative coordinates.

Is there a minimalistic PDF.js sample that supports text selection?

I'm trying PDF.js.
My problem is that the Hello World demo does not support text selection. It will draw everything in a canvas without the text layer. The official PDF.js demo does support text selection but the code is too complex. I was wondering if somebody has a minimalistic demo with the text layer.
I have committed the example to Mozilla's pdf.js repository and it is available under the examples directory.
The original example that I committed to pdf.js no longer exists, but I believe it this example showcases text-selection. They have cleaned up and reorganized pdf.js and so the text-selection logic is encapsulated inside the text-layer, which can be created using a factory.
Specifically, PDFJS.DefaultTextLayerFactory takes care of setting up the basic text-selection stuff.
The following example is outdated; only leaving it here for historical reasons.
I have been struggling with this problem for 2-3 days now, but I finally figured it out. Here is a fiddle that shows you how to load a PDF with text-selection enabled.
The difficulty in figuring this out was that the text-selection logic was intertwined with the viewer code (viewer.js, viewer.html, viewer.css). I had to extricate relevant code and CSS out to get this to work (that JavaScript file is referenced in the file; you can also check it out here). The end result is a minimal demo that should prove helpful. To implement selection properly, the CSS that is in viewer.css is also extremely important as it sets up CSS styles for the divs that are eventually created and then used to get text selection working.
The heavy lifting is done by the TextLayerBuilder object, which actually handles the creation of the selection divs. You can see calls to this object from within viewer.js.
Anyway, here's the code including the CSS. Keep in mind that you will still need the pdf.js file. My fiddle has a link to a version that I built from Mozilla's GitHub repo for pdf.js. I didn't want to link to the repo's version directly since they are constantly developing it and it may be broken.
So without further ado:
HTML:
<html>
<head>
<title>Minimal pdf.js text-selection demo</title>
</head>
<body>
<div id="pdfContainer" class = "pdf-content">
</div>
</body>
</html>
CSS:
.pdf-content {
border: 1px solid #000000;
}
/* CSS classes used by TextLayerBuilder to style the text layer divs */
/* This stuff is important! Otherwise when you select the text, the text in the divs will show up! */
::selection { background:rgba(0,0,255,0.3); }
::-moz-selection { background:rgba(0,0,255,0.3); }
.textLayer {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
color: #000;
font-family: sans-serif;
overflow: hidden;
}
.textLayer > div {
color: transparent;
position: absolute;
line-height: 1;
white-space: pre;
cursor: text;
}
.textLayer .highlight {
margin: -1px;
padding: 1px;
background-color: rgba(180, 0, 170, 0.2);
border-radius: 4px;
}
.textLayer .highlight.begin {
border-radius: 4px 0px 0px 4px;
}
.textLayer .highlight.end {
border-radius: 0px 4px 4px 0px;
}
.textLayer .highlight.middle {
border-radius: 0px;
}
.textLayer .highlight.selected {
background-color: rgba(0, 100, 0, 0.2);
}
JavaScript:
//Minimal PDF rendering and text-selection example using pdf.js by Vivin Suresh Paliath (http://vivin.net)
//This fiddle uses a built version of pdf.js that contains all modules that it requires.
//
//For demonstration purposes, the PDF data is not going to be obtained from an outside source. I will be
//storing it in a variable. Mozilla's viewer does support PDF uploads but I haven't really gone through
//that code. There are other ways to upload PDF data. For instance, I have a Spring app that accepts a
//PDF for upload and then communicates the binary data back to the page as base64. I then convert this
//into a Uint8Array manually. I will be demonstrating the same technique here. What matters most here is
//how we render the PDF with text-selection enabled. The source of the PDF is not important; just assume
//that we have the data as base64.
//
//The problem with understanding text selection was that the text selection code has heavily intertwined
//with viewer.html and viewer.js. I have extracted the parts I need out of viewer.js into a separate file
//which contains the bare minimum required to implement text selection. The key component is TextLayerBuilder,
//which is the object that handles the creation of text-selection divs. I have added this code as an external
//resource.
//
//This demo uses a PDF that only has one page. You can render other pages if you wish, but the focus here is
//just to show you how you can render a PDF with text selection. Hence the code only loads up one page.
//
//The CSS used here is also very important since it sets up the CSS for the text layer divs overlays that
//you actually end up selecting.
//
//For reference, the actual PDF document that is rendered is available at:
//http://vivin.net/pub/pdfjs/TestDocument.pdf
var pdfBase64 = "..."; //should contain base64 representing the PDF
var scale = 1; //Set this to whatever you want. This is basically the "zoom" factor for the PDF.
/**
* Converts a base64 string into a Uint8Array
*/
function base64ToUint8Array(base64) {
var raw = atob(base64); //This is a native function that decodes a base64-encoded string.
var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
for(var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
function loadPdf(pdfData) {
PDFJS.disableWorker = true; //Not using web workers. Not disabling results in an error. This line is
//missing in the example code for rendering a pdf.
var pdf = PDFJS.getDocument(pdfData);
pdf.then(renderPdf);
}
function renderPdf(pdf) {
pdf.getPage(1).then(renderPage);
}
function renderPage(page) {
var viewport = page.getViewport(scale);
var $canvas = jQuery("<canvas></canvas>");
//Set the canvas height and width to the height and width of the viewport
var canvas = $canvas.get(0);
var context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
//Append the canvas to the pdf container div
jQuery("#pdfContainer").append($canvas);
//The following few lines of code set up scaling on the context if we are on a HiDPI display
var outputScale = getOutputScale();
if (outputScale.scaled) {
var cssScale = 'scale(' + (1 / outputScale.sx) + ', ' +
(1 / outputScale.sy) + ')';
CustomStyle.setProp('transform', canvas, cssScale);
CustomStyle.setProp('transformOrigin', canvas, '0% 0%');
if ($textLayerDiv.get(0)) {
CustomStyle.setProp('transform', $textLayerDiv.get(0), cssScale);
CustomStyle.setProp('transformOrigin', $textLayerDiv.get(0), '0% 0%');
}
}
context._scaleX = outputScale.sx;
context._scaleY = outputScale.sy;
if (outputScale.scaled) {
context.scale(outputScale.sx, outputScale.sy);
}
var canvasOffset = $canvas.offset();
var $textLayerDiv = jQuery("<div />")
.addClass("textLayer")
.css("height", viewport.height + "px")
.css("width", viewport.width + "px")
.offset({
top: canvasOffset.top,
left: canvasOffset.left
});
jQuery("#pdfContainer").append($textLayerDiv);
page.getTextContent().then(function(textContent) {
var textLayer = new TextLayerBuilder($textLayerDiv.get(0), 0); //The second zero is an index identifying
//the page. It is set to page.number - 1.
textLayer.setTextContent(textContent);
var renderContext = {
canvasContext: context,
viewport: viewport,
textLayer: textLayer
};
page.render(renderContext);
});
}
var pdfData = base64ToUint8Array(pdfBase64);
loadPdf(pdfData);
Because This is an old question and old accepted answer, to get it working with recent PDF.JS versions you may use this solution
http://www.ryzhak.com/converting-pdf-file-to-html-canvas-with-text-selection-using-pdf-js
Here is the code they used :
Include the following CSS and scripts from the PDF.js code
<link rel="stylesheet" href="pdf.js/web/text_layer_builder.css" />
<script src="pdf.js/web/ui_utils.js"></script>
<script src="pdf.js/web/text_layer_builder.js"></script>
use this code to load the PDF :
PDFJS.getDocument("oasis.pdf").then(function(pdf){
var page_num = 1;
pdf.getPage(page_num).then(function(page){
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = $('#the-canvas')[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var canvasOffset = $(canvas).offset();
var $textLayerDiv = $('#text-layer').css({
height : viewport.height+'px',
width : viewport.width+'px',
top : canvasOffset.top,
left : canvasOffset.left
});
page.render({
canvasContext : context,
viewport : viewport
});
page.getTextContent().then(function(textContent){
console.log( textContent );
var textLayer = new TextLayerBuilder({
textLayerDiv : $textLayerDiv.get(0),
pageIndex : page_num - 1,
viewport : viewport
});
textLayer.setTextContent(textContent);
textLayer.render();
});
});
});
If you want to render all pages of pdf document in different pages with text selection you can use either
pdf viewer
canvas and renderer to parse the text and append it over the canvas, so that it looks like text selection.
But on real scenario, if you are going to process with the canvas like zoom in/out then this canvas operation will terribly reduce your browser performance. please check the below url,
http://learnnewhere.unaux.com/pdfViewer/viewer.html
You could get the complete code from here
https://github.com/learnnewhere/simpleChatApp/tree/master/pdfViewer

Categories