How to stretch text value in konvaJS to certain width and height? - javascript

In KonvaJS Text Object there is a property fontSize like fontSize: 30 but I need to stretch the text according the width and height I give for it.
Here what I wrote:
var textX = new Konva.Text({
text: 'X',
align: 'center',
x: 60,
y: 60,
width: 60,
height: 40
});
What do you suggest to let the code work?

Text fonts may not incrementally scale to exactly fit a desired width, but you can come close.
Create an in-memory canvas element,
Measure your text at a certain px testFontsize (almost any reasonable test size will do),
The needed font size is: testFontsize*desiredWidth/measuredWidth,
Set the needed px font size in your Konva.Text.
Notes: Some fonts do not scale with decimal precision so you might have to .toFixed(0) the resulting scaled font size. Some fonts may not incrementally scale at all and you will get the nearest available font size -- which might not fill the desired width well.
Example code:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// define the desired text, fontsize and width
var text='Scale Me';
var fontface='verdana';
var desiredWidth=60;
$myslider=$('#myslider');
$myslider.attr({min:30,max:200}).val(desiredWidth);
$myslider.on('input change',function(){
desiredWidth=parseInt($(this).val());
ctx.clearRect(0,0,cw,ch);
draw(text,fontface,desiredWidth)
});
draw(text,fontface,desiredWidth);
function draw(text,fontface,desiredWidth){
// calc the scaled fontsize needed to fill the desired width
var scaledSize=scaledFontsize(text,fontface,desiredWidth);
// Demo: draw the text at the scaled fontsize
ctx.font=scaledSize+'px '+fontface;
ctx.textAlign='left';
ctx.textBaseline='middle';
ctx.strokeRect(0,0,desiredWidth,100);
ctx.fillText(text,0,50);
ctx.font='14px verdana';
ctx.fillText(scaledSize+'px '+fontface+' fits '+desiredWidth+'px width',10,125);
}
function scaledFontsize(text,fontface,desiredWidth){
var c=document.createElement('canvas');
var cctx=c.getContext('2d');
var testFontsize=18;
cctx.font=testFontsize+'px '+fontface;
var textWidth=cctx.measureText(text).width;
return((testFontsize*desiredWidth/textWidth));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Desired Width:&nbsp<input id=myslider type=range><br>
<canvas id="canvas" width=300 height=256></canvas>

Related

assign canvas to div, adapt canvas dimensions to div dimenson - how to fix?

I have this example of a canvas as a div background (I forked it from another example, don't remember where I found it):
http://jsfiddle.net/sevku/6jace59t/18/
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var divHeight = document.getElementById('canvas').clientHeight;
var divWidth = document.getElementById('canvas').clientWidth;
function assignToDiv(){ // this kind of function you are looking for
dataUrl = canvas.toDataURL();
document.getElementsByTagName('div')[0].style.background='url('+dataUrl+')'
}
function draw() { // replace with your logic
ctx.fillStyle = "rgb(100, 250, 100)";
ctx.fillRect (10, 10, divWidth-20, divHeight-20);
}
draw()
assignToDiv()
My problem; If I put the dimensions of the div 300 x 150, the canvas does what it is supposed to do. But if I change the dimensions, the canvas is supposed to adapt to the div dimensions. What did I do wrong that this doesn't happen?
PS: I'm a beginner, so please forgive me stupid questions.
It's because if you don't give canvas width and height, it's default to 300x150, so after you get the width and height from div, you should use them to set your canvas' dimensions as well.
Another point worth notice is that you use div.style.background property to set the background image, however, as there's many background related properties (e.g: background-repeat in your jsfiddle, background-position, background-size...), the background can set all of them at once.
When you use div.style.background='url('+dataUrl+')';. It overrides all other background-related properties to initial.
If you want to preserve those properties, you may either reset them after you set style.background, or you can use div.style.backgroundImage to change the background image without affect other background related properties.
jsfiddle
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var divHeight = document.getElementById('canvas').clientHeight;
var divWidth = document.getElementById('canvas').clientWidth;
// VVVV After you get WxH, set the canvas's dimension too.
canvas.width = divWidth;
canvas.height = divWidth;
var div1 = document.getElementById('canvas');
var div2 = document.getElementById('canvas2');
function assignToDiv(div){ // this kind of function you are looking for
var dataUrl = canvas.toDataURL();
div.style.background='url('+dataUrl+')'; // This line will overwrite your background settings.
div.style.backgroundRepeat = 'repeat-x'; // Use this to set background related properties after above.
}
function assignToDivAlt(div){ // this kind of function you are looking for
var dataUrl = canvas.toDataURL();
div.style.backgroundImage = 'url('+dataUrl+')'; // Only set the background-image would have same effect.
}
function draw() { // replace with your logic
ctx.fillStyle = "rgb(100, 250, 100)";
// If you don't set WH, then the canvas would be 300x150, and those
// you drawed but out of boundary are clipped.
ctx.fillRect (10, 10, divWidth-20, divHeight-20);
}
draw()
assignToDiv(div1);
assignToDiv(div2);
canvas {display:none;}
div {
width:600px;
height:550px;
border:1px solid grey;
background-repeat:repeat-x;
}
<canvas></canvas>
<div id="canvas"></div>
<div id="canvas2"></div>

FabricJS: using object controls on canvas to resize, but not scale

The problem is to update the actual object.width, object.height and keep object.scaleX = 1 and object.scaleY = 1 when using the visual controls on the canvas.
The origin of the problem is when manipulating the object using controls, fabric.js changes the scale of the object, as well as scaling the stroke of paths, which I would like to be of the same width always.
So I would like to make it more like Adobe Illustrator-like, and not scale the width of the stroke along with the width of the rectalngular, for example.
I have found a solution to a question formulated in a different manner here:
Rect with stroke, the stroke line is mis-transformed when scaled
The idea is to calculate the new would-be width and height using the new scale factors, set the new dimensions and reset the scale factors to 1.
Here's the code example from that answer:
el.on({
'scaling': function(e) {
var obj = this,
w = obj.width * obj.scaleX,
h = obj.height * obj.scaleY,
s = obj.strokeWidth;
obj.set({
'height' : h,
'width' : w,
'scaleX' : 1,
'scaleY' : 1
});
}
});
From Fabric.js version 2.7.0 you can enable a strokeUniform property on the object this will always match the exact pixel size entered for stroke width.
var circle2 = new fabric.Circle({
radius: 65,
fill: '#4FC3F7',
left: 110,
opacity: 0.7,
stroke: 'blue',
strokeWidth: 3,
strokeUniform: true
});
http://fabricjs.com/stroke-uniform

html canvas shadow/blur won't go away

There is a shadow on the bottom and right sides of a rectangle I've drawn in the canvas on the upper-left hand corner of my window here:
http://thomasshouler.com/datavis/gugg/ratio.html
I haven't set any positive values to the relevant context attributes (shadowBlur, shadowOffsetY, etc.), so what gives?
Canvas code snippet:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.shadowBlur=0;
ctx.shadowOffsetY=0;
var width = 50;
var height = 4;
var grd=ctx.createLinearGradient(0,0,width,0);
grd.addColorStop(0,'#008000');
grd.addColorStop(0.5,'#CCCCCC');
grd.addColorStop(1,'#FF0000');
ctx.fillStyle=grd;
ctx.fillRect(0,0,width,height);
Any wisdom would be greatly appreciated.
It's related to scaling as the canvas is displayed. Your original fragment with a very small gradient and scaled up http://jsfiddle.net/CBzu4/ clearly shows the blurred outline.
Drawing larger (making sure there is no css scaling) it looks fine: http://jsfiddle.net/CBzu4/1/ and the code is the same as yours, just rearranged:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var width = 50 * 8;
var height = 4 * 8;
var grd=ctx.createLinearGradient(0,0,width,0);
grd.addColorStop(0,'#008000');
grd.addColorStop(0.5,'#FFFF00');
grd.addColorStop(1,'#FF0000');
ctx.fillStyle = grd;
ctx.fillRect(5,5,width,height);
Same code, but this time the canvas scaled up with the embedded style: http://jsfiddle.net/CBzu4/2/
<canvas id="myCanvas" style="border: 1px solid red; width: 120%; height: 120%;" width="600" height="80">
The final version is again the same as yours, no css scaling at all and no blurred outline: http://jsfiddle.net/CBzu4/3/

How to create overlapping - not stacking - shapes with canvas?

I'm trying to create an array of shapes that overlap. But I'm having difficulty preventing those shapes stacking on top of one-another.
I guess I want them to mesh together, if that makes sense?
Here's the code:
var overlap_canvas = document.getElementById("overlap");
var overlap_context = overlap_canvas.getContext("2d");
var x = 200;
var y = x;
var rectQTY = 4 // Number of rectangles
overlap_context.translate(x,y);
for (j=0;j<rectQTY;j++){ // Repeat for the number of rectangles
// Draw a rectangle
overlap_context.beginPath();
overlap_context.rect(-90, -100, 180, 80);
overlap_context.fillStyle = 'yellow';
overlap_context.fill();
overlap_context.lineWidth = 7;
overlap_context.strokeStyle = 'blue';
overlap_context.stroke();
// Degrees to rotate for next position
overlap_context.rotate((Math.PI/180)*360/rectQTY);
}
And here's my jsFiddle:
http://jsfiddle.net/Q8yjP/
And here's what I'm trying to achieve:
Any help or guidance would be greatly appreciated!
You cannot specify this behavior but you can implement an algorithmic-ish approach that uses composite modes.
As shown in this demo the result will be like this:
Define line width and the rectangles you want to draw (you can fill this array with the loop you already got to calculate the positions/angles - for simplicity I just use hard-coded ones here):
var lw = 4,
rects = [
[20, 15, 200, 75],
[150, 20, 75, 200],
[20, 150, 200, 75],
[15, 20, 75, 200]
], ...
I'll explain the line width below.
/// set line-width to half the size
ctx.lineWidth = lw * 0.5;
In the loop you add one criteria for the first draw which is also where you change composite mode. We also clear the canvas with the last rectangle:
/// loop through the array with rectangles
for(;r = rects[i]; i++) {
ctx.beginPath();
ctx.rect(r[0], r[1], r[2], r[3]);
ctx.fill();
ctx.stroke();
/// if first we do a clear with last rectangle and
/// then change composite mode and line width
if (i === 0) {
r = rects[rects.length - 1];
ctx.clearRect(r[0] - lw * 0.5, r[1] - lw * 0.5, r[2] + lw, r[3] + lw);
ctx.lineWidth = lw;
ctx.globalCompositeOperation = 'destination-over';
}
}
This will draw the rectangles and you have the flexibility to change the sizes without needing to recalculate clipping.
The line-width is set separately as stroke strokes the line from the middle. Therefor, since we later use destination-over mode it means half of the line won't be visible as we first fill which becomes part of destination so that the stroke will only be able to fill outside the stroked area (you could reverse the order of stroke and fill but will always run into an adjustment for the first rectangle).
We also need it to calculate the clipping which must include (half) the line on the outside.
This is also why we initially set it to half as the whole line will be drawn the first time - otherwise the first rectangle will have double as thick borders.
The only way to do it to cut your rectangles and compute which sub rectangle goes over which one. But I think you will have to draw your borders and inner rectangles separately because separating rectangles will add additional borders.
Hope it helped
Sadly, the feature you want of setting z-indexes on part of an element using canvas is not available currently. If you just need it for the four rectangle object you could do something like this which hides part of the rectangle to fake the effect you want, however this is hard coded to only 4 rectangles.
var overlap_canvas = document.getElementById("overlap");
var overlap_context = overlap_canvas.getContext("2d");
var x = 200;
var y = x;
var rectQTY = 4 // Number of rectangles
overlap_context.translate(x, y);
for (j = 0; j < rectQTY; j++) { // Repeat for the number of rectangles
// Draw a rectangle
overlap_context.beginPath();
overlap_context.rect(-90, -100, 180, 80);
overlap_context.fillStyle = 'yellow';
overlap_context.fill();
overlap_context.lineWidth = 7;
overlap_context.strokeStyle = 'blue';
overlap_context.stroke();
if (j === 3) {
overlap_context.beginPath();
overlap_context.rect(24, -86, 72, 80);
overlap_context.fillStyle = 'yellow';
overlap_context.fill();
overlap_context.closePath();
overlap_context.beginPath();
overlap_context.moveTo(20, -89.5);
overlap_context.lineTo(100, -89.5);
overlap_context.stroke();
overlap_context.closePath();
overlap_context.beginPath();
overlap_context.moveTo(20.5, -93.1);
overlap_context.lineTo(20.5, 23);
overlap_context.stroke();
overlap_context.closePath();
}
// Degrees to rotate for next position
overlap_context.rotate((Math.PI / 180) * 360 / rectQTY);
}
Demo here
If you have to make it dynamic, you could cut the shapes like Dark Duck suggested or you could try to create a function that detects when an object is overlapped and redraw it one time per rectangle (hard to do and not sure if it'd work). Perhaps you could come up with some equation for positioning the elements in relation to how I have them hard coded now to always work depending on the rotation angle, this would be your best bet IMO, but I don't know how to make that happen exactly
Overall you can't really do what you're looking for at this point in time
Using pure JavaScript ...
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="mycanvas" width="400px" height="400px"></canvas>
<script>
window.onload = function(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
//cheat - use a hidden canvas
var hidden = document.createElement('canvas');
hidden.width = 400;
hidden.height = 400;
var hiddenCtx = hidden.getContext('2d');
hiddenCtx.strokeStyle = 'blue';
hiddenCtx.fillStyle = 'yellow';
hiddenCtx.lineWidth = 5;
//translate origin to centre of hidden canvas, and draw 3/4 of the image
hiddenCtx.translate(200,200);
for(var i=0; i<3; i++){
hiddenCtx.fillRect(-170, -150, 300, 120);
hiddenCtx.strokeRect(-170, -150, 300, 120);
hiddenCtx.rotate(90*(Math.PI/180));
}
//reset the hidden canvas to original status
hiddenCtx.rotate(90*(Math.PI/180));
hiddenCtx.translate(-200,-200);
//translate to middle of visible canvas
ctx.translate(200, 200);
//repeat trick, this time copying from hidden to visible canvas
ctx.drawImage(hidden, 200, 0, 200, 400, 0, -200, 200, 400);
ctx.rotate(180*(Math.PI/180));
ctx.drawImage(hidden, 200, 0, 200, 400, 0, -200, 200, 400);
};
</script>
</body>
</html>
Demo on jsFiddle

How to calculate rotationDegree for fillPatternImage of wedges?

I have the following circle, made of wedges. Each wedge has a fillPatternImage. Each fillPatternImage has an image with a centered text. The text varies in length for each wedge.
The problem is I need to give each fillPatternImage a rotation degree so all text aligns perfectly along the circle’s perimeter. But I have no clue what rotation degree to give each fillPatternImage.
For example, when I give all fillPatternImages a rotation degree of 95°, short texts align well, but long texts turn out crooked.
I suppose rotation degree must be dynamic for each fillPatternImage. But I haven’t found out how. I have the wedge dimensions, the text width, etc.
Code example for fillPatternImage:
imageObj.src = Caption + ".png";
imageObj.onload = function () {
nts.setFillPatternImage(imageObj);
nts.setFillPatternRotationDeg(95);
// nts.setFillPatternOffset(-220, 100);
nts.setFillPatternX(radio - 15);
nts.setFillPatternY(leftSide);
nts.setFillPatternRepeat("no-repeat");
nts.draw();
}
Any ideas would be of great help. Thanks in advance.
How to calculate fillPatternRotation angle for a Kinetic Wedge
Your text will always be appropriately rotated in the Kinetic wedge with this fillPatternRotation:
fillPatternRotation:Math.PI/2+wedgeAngleDeg*Math.PI/360
Where wedgeAngleDeg is the value supplied to wedge.angleDeg:
angleDeg: wedgeAngleDeg
You also need to set the appropriate wedge fillPatternOffset to match your text-image
You must horizontally offset the fillPattern to the midpoint of the text on the image
Assuming your text is horizontally centered on your image, that offset is image.width/2.
fillPatternOffset X is image.width/2
You must vertically offset the fillPattern to align the image text to the largest width on the wedge.
You can calculate the largest wedge width like this:
var textTop=radius*Math.sin(wedgeAngleDeg*Math.PI/180);
So your fillPatternOffset becomes:
fillPatternOffset: [image.width/2, image.height-textTop],
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/Y53cH/
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.6.0.min.js"></script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var img=new Image();
img.onload=function(){
start();
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/testing.png";
function start(){
var layer = new Kinetic.Layer();
var wedgeAngleDeg=60;
var radius=100;
var textTop=radius*Math.sin(wedgeAngleDeg*Math.PI/180);
var wedge = new Kinetic.Wedge({
x: stage.getWidth() / 2,
y: stage.getHeight() / 2,
radius: radius,
angleDeg: wedgeAngleDeg,
fillPatternImage: img,
fillPatternOffset: [img.width/2, img.height-textTop],
fillPatternRepeat:"no-repeat",
fillPatternRotation:Math.PI/2+wedgeAngleDeg*Math.PI/360,
stroke: 'black',
strokeWidth: 4,
rotationDeg: 0
});
layer.add(wedge);
wedge.setRotationDeg(-45);
// add the layer to the stage
stage.add(layer);
}
</script>
</body>
</html>

Categories