Best way to serve / produce silhoutte of the US States? - svg

I'm responsible for delivering pages to display primary results for the US elections State by State. Each page needs a banner with an image of the State, approx 250px by 250px. Now all I need to do is figure out how to serve / generate those images...
I've dug into the docs / examples for Protovis and think I
could probably lift the State coordinate outlines- I would have to
manually transform the coordinate data to be justified and sized
properly (ick)
At the other end of the clever/brute spectrum is an enormous sprite
or series of sprites. Even with png 8 compression the file size of
a grid of 50 non-overlapping 250x250px sprites is a concern, and
sadly such a file doesn't seem to exist so I'd have to create it
from hand. Also unpleasant.
Who's got a better idea?
Answered: the right solution is to switch to d3.
What we hacked in for now:
drawStateInBox = function(box, state, color) {
var w = $("#" + box).width(),
h = $("#" + box).height(),
off_x = 0,
off_y = 0;
borders = us_lowres[state].borders;
//Preserve aspect ratio
delta_lat = pv.max(borders[0], function(b) b.lat) - pv.min(borders[0], function(b) b.lat);
delta_lng = pv.max(borders[0], function(b) b.lng) - pv.min(borders[0], function(b) b.lng);
if (delta_lat / h > delta_lng / w) {
scaled_h = h;
scaled_w = w * delta_lat / delta_lng;
off_x = (w - scaled_w) / 2;
} else {
scaled_h = h * delta_lat / delta_lng;
scaled_w = w;
off_y = (h - scaled_h) / 2;
}
var scale = pv.Geo.scale()
.domain(us_lowres[state].borders[0])
.range({x: off_x, y: off_y},
{x: scaled_w + off_x, y: scaled_h + off_y});
var vis = new pv.Panel(state)
.canvas(box)
.width(w)
.height(h)
.data(borders)
.add(pv.Line)
.data(function(l) l)
.left(scale.x)
.top(scale.y)
.fillStyle(function(d, l, c) {
return(color);
})
.lineWidth(0)
.strokeStyle(color)
.antialias(false);
vis.render();
};

d3 seems to have the capability to do maps similar to what you want. The example shows both counties and states so you would just omit the counties and then provide the election results in the right format.

There is a set of maps on 50states.com, e.g. http://www.50states.com/maps/alabama.htm, which is about 5KB. Roughly, then, that's 250KB for the whole set. Since you mention using these separately, there's your answer.
Or are you doing more with this than just showing the outline?

Related

How to animate rectangle to fixed width in steps with createjs?

I'm trying to create loading bar for my game. I create basic rectangle and added to the stage and caluclated size acording to the number of files so I get fixed width. Everything works, but for every step (frame) it creates another rectangle, how do I get only one object?
this is my code:
function test(file) {
r_width = 500;
r_height = 20;
ratio = r_width / manifest.length;
if (file == 1) {
new_r_width = 0
// Draw
r = new createjs.Shape();
r_x = (width / 2) - (r_width / 2);
r_y = (height / 2) - (r_height / 2);
new_r_width += ratio;
r.graphics.beginFill("#222").drawRect(r_x, r_y, new_r_width, r_height);
stage.addChild(r);
} else {
stage.clear();
new_r_width += ratio;
r.graphics.beginFill("#" + file * 100).drawRect(r_x, r_y + file * 20, new_r_width, r_height);
stage.addChild(r);
}
stage.update();
}
https://space-clicker-c9-zoranf.c9.io/loading/
If you want to redraw the rectangle, you will have to clear the graphics first, and then ensure the stage is updated. In your code it looks like you are clearing the stage, which is automatically handled by the stage.update() unless you manually turn off updateOnTick.
There are some other approaches too. If you just use a rectangle, you can set the scaleX of the shape. Draw your rectangle at 100% of the size you want it at, and then scale it based on the progress (0-1).
r.scaleX = 0.5; // 50%
A new way that is supported (only in the NEXT version of EaselJS, newer than 0.7.1 in GitHub), you can save off the drawRect command, and modify it.
var r = new createjs.Shape();
r.graphics.beginFill("red");
var rectCommand = r.graphics.drawRect(0,0,100,10).command; // returns the command
// Later
rectCommand.w = 50; // Modify the width of the rectangle
Hope that helps!

How to make 161 meter / 528ft circles on with OSMDROID?

I'm using OsmDroid on OpenStreetMaps and can make markers and polylines, but I can't find any examples on how I'd make 161m/528ft circles around a marker.
a) How do I make circles?
b) How do I make them 161m/528ft in size?
Thanks to MKer, I got an idea on how to solve the problem and made this piece of code, which works:
oPolygon = new org.osmdroid.bonuspack.overlays.Polygon(this);
final double radius = 161;
ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>();
for (float f = 0; f < 360; f += 1){
circlePoints.add(new GeoPoint(latitude , longitude ).destinationPoint(radius, f));
}
oPolygon.setPoints(circlePoints);
oMap.getOverlays().add(oPolygon);`
I know this can be optimized. I'm drawing 360 points, no matter what the zoom is!
If you want a "graphical" circle, then you can implement easily your own CircleOverlay, using the DirectedLocationOverlay as a very good starting point.
If you want a "geographical" circle (than will appear more or less as an ellipse), then you can use the OSMBonusPack Polygon, that you will define with this array of GeoPoints:
ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>();
iSteps = (radius * 40000)^2;
fStepSize = M_2_PI/iSteps;
for (double f = 0; f < M_2_PI; f += fStepSize){
circlePoints.add(new GeoPoint(centerLat + radius*sin(f), centerLon + radius*cos(f)));
}
(warning: I translated from a Nominatim piece of code in PHP, without testing)

Converting images into a linear color palette with JS, losing colors

The project in question: https://github.com/matutter/Pixel2 is a personal project to replace some out of date software at work. What it should do is, the user adds an image and it generates a color palette of the image. The color palette should have no duplicate colors. (thats the only important stuff)
My question is: why do larger or hi-res or complex images not work as well? (loss of color data)
Using dropzone.js I have the user put a picture on the page. The picture is a thumbnail. Next I use jquery to find the src out of a <img src="...">. I pass that src to a function that does this
function generate(imgdata) {
var imageObj = new Image();
imageObj.src = imgdata;
convert(imageObj); //the function that traverses the image data pulling out RGB
}
the "convert" function pulls out the data fairly simply by
for(var i=0, n=data.length; i<n; i+=4, pixel++ ) {
r = data[i];
g = data[i+1];
b = data[i+2];
color = r + g + b; // format is a string of **r, g, b**
}
finally, the last part of the main algorithme filters out duplicate colors, I only want just 1 occurrence of each... here's the last part
color = monoFilter(color); // the call
function monoFilter(s) {
var unique = [];
$.each(s, function(i, el){
if($.inArray(el, unique) === -1) unique.push(el);
});
unique.splice(0,1); //remove undefine
unique.unshift("0, 0, 0"); //make sure i have black
unique.push("255, 255, 255"); //and white
return unique;
}
I'm hoping someone can help me identify why there is such a loss of color data in big files.
If anyone is actually interesting enough to look at the github, the relivent files are js/pixel2.js, js/dropzone.js, and ../index.html
This is probably the cause of the problem:
color = r + g + b; // format is a string of **r, g, b**
This simply adds the numbers together and the more pixels you have the higher risk you run to get the same number. For example, these colors generate the same result:
R G B
color = 90 + 0 + 0 = 90;
color = 0 + 90 + 0 = 90;
color = 0 + 0 + 90 = 90;
even though they are completely different colors.
To avoid this you can do it like this if you want a string:
color = [r,g,b].join();
or you can create an integer value of them (which is faster to compare with than a string):
color = (b << 16) + (g << 8) + r; /// LSB byte-order
Even an Euclidean vector would be better:
color = r*r + g*g + b*b;
but with the latter you risk eventually the same scenario as the initial one (but useful for nearest color scenarios).
Anyways, hope this helps.
"The problem was that I wasn't accounting for alpha. So a palette from an image that uses alpha would have accidental duplicate records."
I figured this out after finding this Convert RGBA color to RGB

what parameters of CIVignette mean

I check CIVignette of Core Image Filter Reference at
http://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/filter/ci/CIColorControls
and play around a with the parameters:
inputRadius
inputIntensity
and still have not exactly understood what each parameter effects. Could please someone explain?
Take a look at wiki understand what vignetting in photography means.
It is the fall of of light starting from the center of an image towards the corner.
Apple does not explain much about the the params.
obviously the radius specifies somehow where the vignetitting starts
the param intensity i expect to be how fast the light goes down after vignetting starts.
The radius may not be given in points, a value of 1.0 relates to your picture size.
Intensity is definitely something like 1 to 10 or larger number. 1 has some effects, 10 is rather dark already.
The radius seems to be in pixel (or points). I use a portion of image size (says 1/10th of width) and the effect is pretty good! However, if the intensity is strong (says 10), the radius can be small (like 1) and you can still see the different.
Turns out there is an attributes property on CIFilter that explains its properties and ranges.
let filter = CIFilter(name: "CIVignette")!
print("\(filter.attributes)")
Generates the following output:
[
"CIAttributeFilterDisplayName": Vignette,
"CIAttributeFilterCategories": <__NSArrayI 0x6000037020c0>(
CICategoryColorEffect,
CICategoryVideo,
CICategoryInterlaced,
CICategoryStillImage,
CICategoryBuiltIn
),
"inputRadius": {
CIAttributeClass = NSNumber;
CIAttributeDefault = 1;
CIAttributeDescription = "The distance from the center of the effect.";
CIAttributeDisplayName = Radius;
CIAttributeMax = 2;
CIAttributeMin = 0;
CIAttributeSliderMax = 2;
CIAttributeSliderMin = 0;
CIAttributeType = CIAttributeTypeScalar;
},
"CIAttributeFilterName": CIVignette,
"inputImage": {
CIAttributeClass = CIImage;
CIAttributeDescription = "The image to use as an input image. For filters that also use a background image, this is the foreground image.";
CIAttributeDisplayName = Image;
CIAttributeType = CIAttributeTypeImage;
},
"inputIntensity": {
CIAttributeClass = NSNumber;
CIAttributeDefault = 0;
CIAttributeDescription = "The intensity of the effect.";
CIAttributeDisplayName = Intensity;
CIAttributeIdentity = 0;
CIAttributeMax = 1;
CIAttributeMin = "-1";
CIAttributeSliderMax = 1;
CIAttributeSliderMin = "-1";
CIAttributeType = CIAttributeTypeScalar;
},
"CIAttributeFilterAvailable_Mac": 10.9,
"CIAttributeFilterAvailable_iOS": 5,
"CIAttributeReferenceDocumentation": http://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/CIVignette
]
inputRadius is a float between 0 and 2 that affects the 'size' of the shadow.
inputIntensity is a float between -1 and 1 that affects the 'darkness' of the filter.

How to avoid the overlapping of text elements on the TreeMap when child elements are opened in D3.js?

I created a Tree in D3.js based on Mike Bostock's Node-link Tree. The problem I have and that I also see in Mike's Tree is that the text label overlap/underlap the circle nodes when there isn't enough space rather than extend the links to leave some space.
As a new user I'm not allowed to upload images, so here is a link to Mike's Tree where you can see the labels of the preceding nodes overlapping the following nodes.
I tried various things to fix the problem by detecting the pixel length of the text with:
d3.select('.nodeText').node().getComputedTextLength();
However this only works after I rendered the page when I need the length of the longest text item before I render.
Getting the longest text item before I render with:
nodes = tree.nodes(root).reverse();
var longest = nodes.reduce(function (a, b) {
return a.label.length > b.label.length ? a : b;
});
node = vis.selectAll('g.node').data(nodes, function(d, i){
return d.id || (d.id = ++i);
});
nodes.forEach(function(d) {
d.y = (longest.label.length + 200);
});
only returns the string length, while using
d.y = (d.depth * 200);
makes every link a static length and doesn't resize as beautiful when new nodes get opened or closed.
Is there a way to avoid this overlapping? If so, what would be the best way to do this and to keep the dynamic structure of the tree?
There are 3 possible solutions that I can come up with but aren't that straightforward:
Detecting label length and using an ellipsis where it overruns child nodes. (which would make the labels less readable)
scaling the layout dynamically by detecting the label length and telling the links to adjust accordingly. (which would be best but seems really difficult
scale the svg element and use a scroll bar when the labels start to run over. (not sure this is possible as I have been working on the assumption that the SVG needs to have a set height and width).
So the following approach can give different levels of the layout different "heights". You have to take care that with a radial layout you risk not having enough spread for small circles to fan your text without overlaps, but let's ignore that for now.
The key is to realize that the tree layout simply maps things to an arbitrary space of width and height and that the diagonal projection maps width (x) to angle and height (y) to radius. Moreover the radius is a simple function of the depth of the tree.
So here is a way to reassign the depths based on the text lengths:
First of all, I use the following (jQuery) to compute maximum text sizes for:
var computeMaxTextSize = function(data, fontSize, fontName){
var maxH = 0, maxW = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none',
margin:0,
padding:0
});
$(div).css("font", fontSize + 'px '+fontName);
data.forEach(function(d) {
$(div).html(d);
maxH = Math.max(maxH, $(div).outerHeight());
maxW = Math.max(maxW, $(div).outerWidth());
});
$(div).remove();
return {maxH: maxH, maxW: maxW};
}
Now I will recursively build an array with an array of strings per level:
var allStrings = [[]];
var childStrings = function(level, n) {
var a = allStrings[level];
a.push(n.name);
if(n.children && n.children.length > 0) {
if(!allStrings[level+1]) {
allStrings[level+1] = [];
}
n.children.forEach(function(d) {
childStrings(level + 1, d);
});
}
};
childStrings(0, root);
And then compute the maximum text length per level.
var maxLevelSizes = [];
allStrings.forEach(function(d, i) {
maxLevelSizes.push(computeMaxTextSize(allStrings[i], '10', 'sans-serif'));
});
Then I compute the total text width for all the levels (adding spacing for the little circle icons and some padding to make it look nice). This will be the radius of the final layout. Note that I will use this same padding amount again later on.
var padding = 25; // Width of the blue circle plus some spacing
var totalRadius = d3.sum(maxLevelSizes, function(d) { return d.maxW + padding});
var diameter = totalRadius * 2; // was 960;
var tree = d3.layout.tree()
.size([360, totalRadius])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
Now we can call the layout as usual. There is one last piece: to figure out the radius for the different levels we will need a cumulative sum of the radii of the previous levels. Once we have that we simply assign the new radii to the computed nodes.
// Compute cummulative sums - these will be the ring radii
var newDepths = maxLevelSizes.reduce(function(prev, curr, index) {
prev.push(prev[index] + curr.maxW + padding);
return prev;
},[0]);
var nodes = tree.nodes(root);
// Assign new radius based on depth
nodes.forEach(function(d) {
d.y = newDepths[d.depth];
});
Eh voila! This is maybe not the cleanest solution, and perhaps does not address every concern, but it should get you started. Have fun!

Resources