Consider having a large (2000x1000) stage with some text in it. The stage gets downscaled to 1000x500 making the text unreadable. Then we try to enlarge the text by zooming it in.
Expected: the text should become readable again at some point.
Actual: the text remains unreadable (blurred) no matter how much we zoom in.
Try zooming the page in (with native browser zoom on desktop) after running the snippet:
const stage = new Konva.Stage({
container: 'container',
width: 2000,
height: 1000,
});
const layer = new Konva.Layer();
stage.add(layer);
const rect = new Konva.Text({
x : 50, y : 50, width: 100, height: 100,
fontSize: 12,
text: "This text should be readable when the viewport gets downscaled"
});
layer.add(rect).draw();
stage.scale({x: 0.5, y: 0.5});
stage.setAttrs({width: 1000, height: 500});
stage.draw();
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.6.0/konva.js"></script>
<div id="container"></div>
The quality loss can be avoided by downscaling with CSS only, like this:
const stage = new Konva.Stage({
container: 'container',
width: 2000,
height: 1000,
});
const layer = new Konva.Layer();
stage.add(layer);
const rect = new Konva.Text({
x : 50, y : 50, width: 100, height: 100,
fontSize: 12,
text: "This text should be readable when the viewport gets downscaled"
});
layer.add(rect).draw();
stage.getChildren().forEach(function(layer) {
layer.canvas._canvas.style.width = "1000px";
layer.canvas._canvas.style.height = "500px";
layer.hitCanvas.setSize(1000, 500);
layer.hitCanvas.context.scale(0.5, 0.5);
});
stage.draw();
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.6.0/konva.js"></script>
<div id="container"></div>
Note how text becomes readable at a certain level of zooming.
The workaround breaks Konvajs abstraction. What problems it can potentially cause? Is there a better way, which uses only public methods exposed by Konvajs?
In fabric.js it can be done like this (complete example here):
canvas.setDimensions({width: '1000px', height: '500px'}, {cssOnly: true});
Konva is a canvas framework. Canvas is a bitmap image unlike vector elements like SVG. So that "blur" should be expected. Technically to fix the issue you can redraw stage with higher pixelRatio on zoom event:
Konva.pixelRatio = 4
stage.draw();
That code will generate more pixels for canvas element. But the page may be very heavy in RAM in this case because Konva will have to produce very large canvas. In most of the mobile apps, you don't need native zooming and you can use responsive design. For zooming the stage, you can use Konva methods.
So, I am trying to position HTML in the viewer to almost make it look like it is part of the scene. So, when you move the camera, I want the position of it, in terms of the viewer, to stay where it is. Now, I have tried to shift the HTML to emulate this when the camera moves; however, I am not sure if my equation is not right or if I am not there. It seems to shift slightly, but not nearly as much as it should when the camera moves. In other words, if I were to put html on top of a cube in the viewer, and move the camera, I want to html to follow the cube. This is what I have tried:
this.viewer.addEventListener(av.CAMERA_CHANGE_EVENT, function(e){
console.log($(`.draggable`).attr(`originalPos`));
console.log(e.camera);
var width = window.innerWidth, height = window.innerHeight;
var widthHalf = width / 2, heightHalf = height / 2;
let originalPos = $(`.draggable`).attr(`originalPos`).split(` `);
let originalX = originalPos[0];
let originalY = originalPos[1];
$(`.draggable`).css(`position`, `absolute`);
let pixelX = (e.camera.position.x * .0005 + .5) * e.target.container.clientWidth;
let pixelY = (e.camera.position.y * -.009 + .5) * e.target.container.clientHeight;
$(`.draggable`).css(`left`, e.camera.position.x + pixelX);
$(`.draggable`).css(`top`, e.camera.position.y + pixelY);
});
$(`#viewer .adsk-viewing-viewer`).append(`<h1 originalPos = "50px 100px" class = "draggable" style="position: absolute; top: 50px; left: 100px;">Test</h1>`);
But this just not seem to have the correct scaling. It doesn't stay in the position I want it to. I have seen this similar concept in your MarkupsCore tool you have made, and also the area measurement tool seems to have some html that positions based on the camera. How do you do this?
Take a look at this blog article:
https://forge.autodesk.com/blog/3d-markup-icons-and-info-card
It has source code and an example repo, that shows, how to position an HTML DIV element to appear stuck to the 3D object in the Forge Viewer.
I'm trying to place text dynamically into an svg created by Snap, this is what I tried:
this.setContent(
`<svg id="${this.svgId}"></svg>`
);
var snap = Snap($(`#${this.svgId}`)[0]);
text = "asdfsdfsdsfd";
var rect = snap.paper.rect(0, 0, 50, text.length*3 + 4, 10);
snap.text(1.5,10, text);
console.log("rect", rect);
console.log("snap", snap);
rect.attr({
fill: "#FFFFFF",
fillOpacity: 0.6,
});
I get this:
I want the rectangle to be just a little bigger than the text, but there must be a better way to do it than to calculate the length and height of the text, and that's assuming the font size won't change.
This is the only result I found regarding text in the snap docs: http://snapsvg.io/docs/#Paper.text
You could try using getBBox() on the text element, and use that to figure the size of the rect. getBBox() wll give you the x,y,width,height,x2,y2 figures to help.
var text = s.text(0,0,'blah blah')
var bb = text.getBBox();
var rect = s.rect(bb.x, bb.y, bb.width, bb.height )
Adjusting with offsets for whatever padding etc that you want. You may also need to allow for stroke widths, as I don't think that's included.
I'm trying to create a simple pdf doc using javascript. I found jsPDF but I don't figure out how to center text. Is it possible?
Yes it's possible. You could write a jsPDF plugin method to use.
One quick example is this:
(function(API){
API.myText = function(txt, options, x, y) {
options = options ||{};
/* Use the options align property to specify desired text alignment
* Param x will be ignored if desired text alignment is 'center'.
* Usage of options can easily extend the function to apply different text
* styles and sizes
*/
if( options.align == "center" ){
// Get current font size
var fontSize = this.internal.getFontSize();
// Get page width
var pageWidth = this.internal.pageSize.width;
// Get the actual text's width
/* You multiply the unit width of your string by your font size and divide
* by the internal scale factor. The division is necessary
* for the case where you use units other than 'pt' in the constructor
* of jsPDF.
*/
txtWidth = this.getStringUnitWidth(txt)*fontSize/this.internal.scaleFactor;
// Calculate text's x coordinate
x = ( pageWidth - txtWidth ) / 2;
}
// Draw text at x,y
this.text(txt,x,y);
}
})(jsPDF.API);
And you use it like this
var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);
This works in the scratchpad on the jsPdf homepage:
var centeredText = function(text, y) {
var textWidth = doc.getStringUnitWidth(text) * doc.internal.getFontSize() / doc.internal.scaleFactor;
var textOffset = (doc.internal.pageSize.width - textWidth) / 2;
doc.text(textOffset, y, text);
}
I have found that the current version of jsPdf supports a parameter 'align' with the function signature like this:
API.text = function (text, x, y, flags, angle, align)
So the following should give you a center-aligned text:
doc.text('The text', doc.internal.pageSize.width, 50, null, null, 'center');
However, at the current point in time, an error is thrown in the library when strict mode is on because a 'var' is missing.
There is an issue and pull request for it, but the fix hasn't made it in:
https://github.com/MrRio/jsPDF/issues/575
Whoever is looking for this, one day, you might be able to use this to make it easier to center text.
WootWoot, just in case you need more layout options, you could also take a look at my pdfmake library
It supports:
text alignments, lists, margins
styling (with style inheritance)
tables with auto/fixed/star sized columns, auto-repeated headers, col/row spans
page headers and footers
font embedding, and a couple of other options
It works on client-side (pure JS) or server-side (an npm module)
Take a look at the playground to see what's possible
Good luck
I had the same problem and a lot of others while creating PDF-Files (e.g. auto-pagebreak, total-pageCount). So i started writing a little lib, which depends on jsPDF but gives you a lot of features in a way you know them (form HTML/CSS and jQuery). You can find it on GitHub. I hope it makes PDF-Creating easier... =)
Based on #Tsilis answer I have snippet out a plugin here https://gist.github.com/Purush0th/7fe8665bbb04482a0d80 which can align the text left, right and center in the given text container width.
(function (api, $) {
'use strict';
api.writeText = function (x, y, text, options) {
options = options || {};
var defaults = {
align: 'left',
width: this.internal.pageSize.width
}
var settings = $.extend({}, defaults, options);
// Get current font size
var fontSize = this.internal.getFontSize();
// Get the actual text's width
/* You multiply the unit width of your string by your font size and divide
* by the internal scale factor. The division is necessary
* for the case where you use units other than 'pt' in the constructor
* of jsPDF.
*/
var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
if (settings.align === 'center')
x += (settings.width - txtWidth) / 2;
else if (settings.align === 'right')
x += (settings.width - txtWidth);
//default is 'left' alignment
this.text(text, x, y);
}
})(jsPDF.API, jQuery);
Usage
var doc = new jsPDF('p', 'pt', 'a4');
//Alignment based on page width
doc.writeText(0, 40 ,'align - center ', { align: 'center' });
doc.writeText(0, 80 ,'align - right ', { align: 'right' });
//Alignment based on text container width
doc.writeText(0, 120 ,'align - center : inside container',{align:'center',width:100});
maybe... just for easy way, you can read this jsPdf text api doc
doc.text(text, x, y, optionsopt, transform)
where optionspot is an option objet, so, you can do this
{align:"center"}
i.e:
doc.text("Hello Sun", doc.internal.pageSize.getWidth()/2, 10, { align: "center" })
where: doc.internal.pageSize.getWidth() is the page width for pdf sheet
doc.text(text,left,top,'center') can be used to center text. It can be used with array of lines as well but when it is used with array the center does not work right so I have used it in a loop for every object in the array.
var lMargin=15; //left margin in mm
var rMargin=15; //right margin in mm
var pdfInMM=210; // width of A4 in mm
var pageCenter=pdfInMM/2;
var doc = new jsPDF("p","mm","a4");
var paragraph="Apple's iPhone 7 is officially upon us. After a week of pre-orders, the latest in the iPhone lineup officially launches today.\n\nEager Apple fans will be lining up out the door at Apple and carrier stores around the country to grab up the iPhone 7 and iPhone 7 Plus, while Android owners look on bemusedly.\n\nDuring the Apple Event last week, the tech giant revealed a number of big, positive changes coming to the iPhone 7. It's thinner. The camera is better. And, perhaps best of all, the iPhone 7 is finally water resistant.\n\nStill, while there may be plenty to like about the new iPhone, there's plenty more that's left us disappointed. Enough, at least, to make smartphone shoppers consider waiting until 2017, when Apple is reportedly going to let loose on all cylinders with an all-glass chassis design.";
var lines =doc.splitTextToSize(paragraph, (pdfInMM-lMargin-rMargin));
var dim = doc.getTextDimensions('Text');
var lineHeight = dim.h
for(var i=0;i<lines.length;i++){
lineTop = (lineHeight/2)*i
doc.text(lines[i],pageCenter,20+lineTop,'center'); //see this line
}
doc.save('Generated.pdf');
Do this:
First get the page width, get half the page width and use it as the x value, use y value of your choice and pass center as the third param to center your text.
Read more from documentation
let doc = new jsPDF();
let pageWidth = doc.internal.pageSize.getWidth();
doc.text("My centered text",pageWidth / 2, 20, 'center');
This will work fine.
let pdf = new jspdf('p', 'mm', 'a4');
pdf.text("Text to display", pdf.internal.pageSize.getWidth() / 2, 50, null, 'center');
50 is the height i.e. y-axis.
This worked for me:
doc.styles.tableBodyEven = {
alignment: 'center'
}
doc.styles.tableBodyOdd = {
alignment: 'center',
color: '#555555',
fillColor: '#dedede'
}
how I can change the width and the height of icons from free Raphael icons ?
I tried to use attr, tried to use % , like this var paper = Raphael("canvas", 100%, 100%);.
I need to do this: if I change the size of the parent block, the size of my icon changes too.
upd: i tried use "scale" and "transform", but icon resize from centre and not fit into the parent correctly
According to the Raphael.js documentation
var el = paper.rect(10, 20, 300, 200);
// translate 100, 100, rotate 45°, translate -100, 0
el.transform("t100,100r45t-100,0");
// if you want you can append or prepend transformations
el.transform("...t50,50");
el.transform("s2...");
// or even wrap
el.transform("t50,50...t-50-50");
// to reset transformation call method with empty string
el.transform("");
// to get current value call it without parameters
console.log(el.transform());
Check this Fiddle:
Demonstration of all the transformations
var icon = paper.rect(100,200,100,100);
var anim = Raphael.animation({
"10%":{transform:'t100,0'}, //transform on x-axis
"20%":{transform:'...t0,100'},//transform on y-axis
"30%":{transform:'...t-100,0'},//transform on x-axis(negative)
"40%":{transform:'...t0,-100'},//transform on y-axis(negative)
"50%":{transform:'...t200,200'},//transform diagonally
"60%":{transform:'...t-100,-100'},//transform diagonally(negative)
"70%":{transform:'...s1,1.5'},//scale y-axis
"80%":{transform:'...s1.5,1'},//scale x-axis
"90%":{transform:'...s2'},//scale in both direction
"100%":{transform:'...r45'},//rotate
},5000);
icon.animate(anim.delay(1000));
So in your case you'll have to do this:
var somename = paper.path("path coordinates").transform('s2,3');
where 2 is for width & 3 is for height.