I need to 'scale' text to fill an antire HTML5 canvas. It appears that the scale() method does not affect text. I've seen approximation methods with iterative loops on the measureText() method but this doesn't get me exactly what I need. Ideally I'd like to fill both horizontally and vertically without conserving the aspect ratio. Would SVG possibly be able to help with this?
My bad - Scale DOES apply to text. I've come up with a solution:
context.font = "20px 'Segoe UI'";
var metrics = context.measureText("Testing!");
var textWidth = metrics.width;
var scalex = (canvas.width / textWidth);
var scaley = (canvas.height / 23);
var ypos = (canvas.height / (scaley * 1.25));
context.scale(scalex, scaley);
context.fillText("Testing!", 0, ypos);
Scale does affect text. Try this:
var can = document.getElementById('test');
var ctx = can.getContext('2d');
ctx.fillText("test", 10, 10); // not scaled text
ctx.scale(3,3);
ctx.fillText("test", 10, 10); // scaled text
See it in action here:
http://jsfiddle.net/3zeBk/8/
Related
I am a fabric.js novice, I have got through a great deal of documentation and code samples, but still can't figure out how can I achieve such simple goal.
I start from a DOM canvas, and would like to obtain a downsized canvas, using the lanczos filter.
var canvas = /* a DOM canvas, obtained through prior processing */
var width = /* target width, smaller than source canvas width */
var height = /* target height, smaller than source canvas height */
I create the filter:
var filter = new fabric.Image.filters.Resize();
filter.resizeType = 'lanczos';
filter.LanczosLobes = 3;
I calculate the scaling:
var scalingX = width / canvas.width;
var scalingY = height / canvas.height;
Now it is not clear to me how can I apply the filter to the canvas, and get the downsized canvas.
Or could someone suggest another javascript library or function, as simple as possible, to perform a canvas-to-canvas lanczos downsize?
I want to add a label that doesn't always face the camera. Instead, I want it to follow a defined path. Similar to how street names follow the direction of their streets in google maps (they aren't always horizontal).
I can think of 2 possible implementations for rotating text but haven't had any luck.
That Label() or label : have a rotation property I haven't found. IE something like this:
viewer.entities.add({
position : Cesium.Cartesian3.fromDegrees(-75.1641667, 39.9522222),
label : {
text : 'Philadelphia'
//rotation : Cesium.Math.toRadians(-45)
}
});
or this
var labels = scene.primitives.add(new Cesium.LabelCollection());
var l = labels.add({
position : Cesium.Cartesian3.fromRadians(longitude, latitude, height),
text : 'Hello World',
font : '24px Helvetica'
//rotation: Cesium.Math.toRadians(-45)
});
Create Pictures of each label in photoshop and import them as an image, then rotate the image (or use it as a material and rotate the entity). Very labor intensive if you have a lot of labels (like street names).
Or perhaps there is a way for cesiumjs to recognize text as a fixed position 2D object and skew it appropriately as the view angle changes.
Any ideas?
If your text doesn't change, You can use an image, and load it by Cesium.SingleTileImageryProvider .
If your text does change, you can use a billboard.image, set an HTML canvas to it, and rotate the canvas like so:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("Hello World!", 10, 50);
ctx.font = "30px Verdana";
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.rotate(20*Math.PI/180);
ctx.fillStyle = gradient;
ctx.fillText("Big smile!", 10, 90);
billboard.image = ctx;
The only way I know how to rotate a label is like #Henri Aloni said with canvas.
Cesium has already a function called: writeTextToCanvas.
example in typescript :
viewer.entities.add({
position: Cartesain3.fromDegrees(34, 32, 0),
billboard: {
image: writeTextToCanvas('baruch', {
font: '30px sans-serif'
}),
rotation: 45
}
});
I'm trying to scale this speech bubble into existence. I'm not really sure how to do it because the default d3 scale is changing the area where it starts drawing.
var svgHeight = 1000
var svgWidth = 1000
var floatycircleRadius = 30
var textColor = "#FFFFFF"
var svg = d3.select("body").append("svg")
.attr("width", svgHeight)
.attr("height", svgWidth)
var floatycontainer = svg.append("g");
var floatygroup = floatycontainer.append("g")
var floatypath = floatygroup.append("path")
.attr("d", "m125.512,0h-66C26.645,0,0,26.482,0,59.35c0,28.574,20.142,52.312,47,58.029V145l26.283-26.283, l52.229,0.064c32.868,0,59.512-26.563,59.512-59.431S158.38,0,125.512,0z")
.style("fill", "#90C4E4")
floatygroup.attr("transform", "translate(500, 500)")
floatycontainer.attr("transform", "scale(1)");
floatycontainer.transition().duration(2000).attr("transform", "0")
Use transition.attrTween(name, tween) on the <g> or <path> element.
.attrTween("transform", function(d, i, a) {
return d3.interpolateString(a, 'scale(1)');
});
http://jsfiddle.net/Wexcode/2jFP5/
So the problem wasn't that I couldn't get the item to scale. It's that when the item was scaling the "M" attribute was also shifting and the svg element was flying across the page due to mixed relative and absolute points on the path.
After changing the line manually to all relative so I could finish my project I found a javascript script to change all paths to relative. Then I could manually change the "M" attribute to 0 so the scale would work correctly source (Convert SVG Path to Relative Commands).
I modified the script to better suit my needs and build this simple page using gist.github.com and bl.ocks.org so it's a simple site to get the all relative path. It fits my long term use case and I thought I'd share it for those interested. Thanks for your help.
http://bl.ocks.org/TheMcMurder/6393419 (live page to convert)
I am having problems drawing a terrain with XNA, specifically with colors (It happens with VertexPositionColorNormal and with VertexPositionTextureNormal). My code is following:
public BasicEffect GetEffectForColoredTerrain()
{
this.coloredTerrainEffect.EnableDefaultLighting();
this.coloredTerrainEffect.SpecularPower = 0.01f; //Power of the light
this.coloredTerrainEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f); //Color of the light when it reflects on a surface
this.coloredTerrainEffect.EmissiveColor = new Vector3(1, 0, 0);
this.coloredTerrainEffect.DirectionalLight0.Enabled = true; //Enable directional light
this.coloredTerrainEffect.DirectionalLight0.DiffuseColor = (new Vector3(0.2f, 0.2f, 0.2f)); //Diffuse color
this.coloredTerrainEffect.DirectionalLight0.SpecularColor = (new Vector3(0.2f, 0.2f, 0.2f)); //Specular color
this.coloredTerrainEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(1, -1f, 1)); //Direction where the light comes from.
this.coloredTerrainEffect.View = Camera.GetInstance().GetViewMatrix();
this.coloredTerrainEffect.Projection = Camera.GetInstance().GetProjectionMatrix();
this.coloredTerrainEffect.Alpha = (float)((float)Configuration.GetInstance().TerrainOpacity / (float)100);
this.coloredTerrainEffect.VertexColorEnabled = true;
return this.coloredTerrainEffect;
}
And this code for drawing terrain:
RasterizerState rs = new RasterizerState();
rs.CullMode = CullMode.None;
WorldContent.CommonGraphicsDevice.RasterizerState = rs;
//Restore things that SpriteBatch can have overriden
WorldContent.CommonGraphicsDevice.BlendState = BlendState.AlphaBlend;
WorldContent.CommonGraphicsDevice.DepthStencilState = DepthStencilState.Default;
WorldContent.CommonGraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
BasicEffect shader = ShadersHandler.GetInstance().GetEffectForColoredTerrain();
foreach (EffectPass pass in shader.CurrentTechnique.Passes)
{
pass.Apply();
WorldContent.CommonGraphicsDevice.Indices = indexBufferVertices;
WorldContent.CommonGraphicsDevice.SetVertexBuffer(vertexBufferVertices);
WorldContent.CommonGraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexPositionColorNormalList.Length, 0, indicesVertices.Length / 3);
}
However, the result is really weird, as you can see in the following images:
Terrain laterally
Terrain bottom
Color is a gradient from Yellow to white (yellow up, white down). However, if I use the effects file from Riemers tutorial (effects.fx from 3D Series 1), everything is correct, as you can see here:
Terrain good laterally
Terrain good bottom
If you wish, you can see the effect code here: Effects file
So QUESTION: Does anyone knows what is happening here with BasicEffect? I would like to use the Riemers file (everything seems correct with it), but I need to use transparency and the BasicEffect object provides me alpha property, which is perfect for what I am looking for.
PD: The same problem happens with textured terrain, using VertexPositionNormalTexture
Looking at the images, the discoloration appears to be a very nice circle, as from a directional light. I would try removing the DirectionalLight0 property settings you are using in the BasicEffect example and see if that corrects the discoloration.
I m using fabric.js in one of my projects.
I m using zooming functionalities . I would like to know if there a simple way to zoom all the canvas (with all the elements ) in on click.
Try out this jsfiddle demonstrating zoom onclick of a button: http://jsfiddle.net/cmontgomery/H7Utw/1/. In essence you get all objects on the canvas and scale/move them by the same factor, giving the visual appearance of zoom.
var objects = canvas.getObjects();
for (var i in objects) {
var scaleX = objects[i].scaleX;
var scaleY = objects[i].scaleY;
var left = objects[i].left;
var top = objects[i].top;
var tempScaleX = scaleX * SCALE_FACTOR;
var tempScaleY = scaleY * SCALE_FACTOR;
var tempLeft = left * SCALE_FACTOR;
var tempTop = top * SCALE_FACTOR;
objects[i].scaleX = tempScaleX;
objects[i].scaleY = tempScaleY;
objects[i].left = tempLeft;
objects[i].top = tempTop;
objects[i].setCoords();
}
canvas.renderAll();
If you use zoom with fabricjs without modifying all objects use: https://github.com/wojtek-krysiak/fabricjs-viewport.
Example: http://wojtek-krysiak.github.io/fabricjs-viewport/