Skip to content

Instantly share code, notes, and snippets.

@andipollok
Last active December 29, 2015 10:58
Show Gist options
  • Select an option

  • Save andipollok/7660324 to your computer and use it in GitHub Desktop.

Select an option

Save andipollok/7660324 to your computer and use it in GitHub Desktop.
Zoomable Labeled Dots

Added text labels to the dots, that show and hide depending on zoom level. Semantic zooming of random positioned clusters with connected dots.

<!DOCTYPE html>
<meta charset="utf-8">
<title></title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
.link {
fill:none;
stroke: #DDD;
stroke-width:1px;
}
text {
font-family: Helvetica, Arial, sans-serif;
font-size: 11px;
}
</style>
<body>
<script>
var width = 960,
height = 500;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([0.5, 5])
.on("zoom", update);
var color = d3.scale.category10();
var line = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); })
.interpolate("linear");
/* ************ Constellation ************ */
var Constellation = function(id, x, y) {
this.id = id;
this.x = x;
this.y = y;
this.dimension = Math.random()*0.3 + 0.1;
this.stars = [];
this.createStars(6);
}
Constellation.prototype.createStars = function(number) {
for (var i=0; i<number; i++) {
var xPos = this.x + Math.random()*this.dimension - this.dimension / 2;
var yPos = this.y + Math.random()*this.dimension - this.dimension / 2;
this.stars.push(new Star(this, i, xPos, yPos));
}
}
/* ************ Star ************ */
var Star = function(parent, id, x, y) {
this.parent = parent;
this.id = id;
this.x = x || 0;
this.y = y || 0;
}
/* ************* INIT NOUNS ****** */
var nouns = [];
d3.text('nouns.txt')
.get(function(error, rows) {
nouns = rows.split('\n');
for(var i in nouns){
if(nouns[i].substring(0, 2) === '//') {
nouns.splice(i,1);
break;
}
}
initNames();
});
/* ************ SVG ************ */
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.call(zoom);
var constellations = [];
for (var i = 0; i<6; i++) {
constellations.push( new Constellation(i, Math.random()*0.6+0.2,Math.random()*0.6+0.2) );
}
var container = svg.selectAll("constellations")
.data(constellations)
.enter().append("g");
var link = container.append("path")
.attr("class", "link");
var star = container.selectAll(".star")
.data(function(d) { return d.stars; })
.enter().append("g")
.attr("class", "star");
var constellation = container.append("g");
constellation.append("circle")
.attr("r", 8)
.style("fill", function(d) { return color(d.id); });
star.append("circle")
.attr("class", "star")
.attr("r", 3 )
.style("fill", function(d) { return color(d.parent.id); });
constellation.append("text")
.attr("text-anchor", "middle")
.attr("y", "20px")
.attr("class", "constellationText");
star.append("text")
.attr("class", "starText")
.attr("text-anchor", "middle")
.attr("y", "15px")
.style("opacity", 0);
update();
function update() {
constellation.attr("transform", transform);
star.attr("transform", transform);
link.attr("d", function(d) { return line(d.stars); } )
if (zoom.scale() < 2) {
constellation.selectAll("text").transition().style("opacity",1).ease("linear");
star.selectAll("text").transition().style("opacity",0).ease("linear");
}
else {
constellation.selectAll("text").transition().style("opacity",0).ease("linear");
star.selectAll("text").transition().style("opacity",1).ease("linear");
}
};
function transform(d) {
return "translate(" + x(d.x) + "," + y(d.y) + ")";
}
function initNames() {
svg.selectAll(".starText").text(function(d) {
return getRandomName();
});
svg.selectAll(".constellationText").text(function(d) {
return getRandomName();
});
}
function getRandomName() {
return nouns[randomInt(0, nouns.length-1)].capitalize() + " " + nouns[randomInt(0, nouns.length-1)].capitalize();
}
// http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
// http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
// Source: http://www.free-teacher-worksheets.com/support-files/list-of-nouns-1.pdf
aardvark
air
airplane
airport
alarm
alligator
alphabet
ambulance
animal
ankle
army
answer
ant
antelope
apple
arm
armchair
arrow
asparagus
baby
back
backbone
bacon
badge
badger
bag
bagpipe
bait
bakery
ball
balloon
bamboo
banana
band
bandana
bangle
banjo
bank
baseball
basket
basketball
bat
bath
bathroom
bathtub
battery
battle
bay
beach
bead
bean
bear
beard
beast
beat
beauty
beaver
bed
bedroom
bee
beef
beetle
bell
belt
bench
beret
berry
bicycle
bike
bird
birthday
bite
black
blade
blanket
block
blood
blouse
blow
board
boat
bobcat
body
bolt
bone
bonsai
book
bookcase
booklet
boot
border
bottle
bottom
boundary
bow
bowling
box
boy
brain
brake
branch
brass
bread
break
breakfast
breath
brick
bridge
broccoli
brochure
brother
brush
bubble
bucket
building
bulb
bull
bulldozer
bumper
bun
bus
bush
butter
button
cabbage
cactus
cafe
cake
calculator
calendar
calf
call
camel
camera
camp
candle
canoe
canvas
cap
captain
car
card
cardboard
cardigan
carpenter
carrot
cartoon
cat
caterpillar
cathedral
cattle
cauliflower
cave
CD
ceiling
celery
cello
cement
cemetery
cereal
chain
chair
chalk
channel
character
cheek
cheese
cheetah
cherry
chess
chest
chick
chicken
children
chimpanzee
chin
chive
chocolate
church
cicada
cinema
circle
city
clam
clarinet
click
clock
close
closet
cloth
cloud
cloudy
coach
coal
coast
coat
cobweb
cockroach
cocoa
coffeecoil
coin
coke
cold
collar
college
colt
comb
comics
comma
computer
copy
corn
cost
cotton
couch
cougar
country
course
court
cousin
cow
crab
crack
cracker
crate
crayfish
crayon
cream
creek
cricket
crocodile
crop
crow
crowd
crown
cucumber
cup
cupboard
curtain
curve
cushion
cyclone
dad
daffodil
daisy
dance
daughter
day
deer
denim
dentist
desert
desk
dessert
detective
dew
diamond
dictionary
dinghy
dinosaur
dirt
dish
dog
doll
dollar
door
dragon
dragonfly
drain
drawer
dream
dress
dresser
drill
drink
drum
dryer
duck
duckling
dungeon
dust
eagle
ear
earth
earthquake
eel
egg
eggplant
elbow
elephant
energy
engine
equipment
evening
eye
eyebrow
face
fact
factory
fairies
family
fan
fang
farm
fear
feast
feather
feet
ferryboat
field
fight
finger
fire
fireplace
fish
flag
flame
flood
floor
flower
flute
fly
foam
fog
food
foot
football
forehead
forest
fork
fountain
fox
frame
freckle
freezer
frog
frost
fruit
fuel
fur
furniture
game
garage
garden
garlic
gas
gate
gear
ghost
giraffe
girl
glass
glove
glue
goal
goat
gold
goldfish
golf
gorilla
government
grape
grass
grasshopper
grease
grill
group
guitar
gum
gym
gymnast
hail
hair
haircut
hall
hamburger
hammer
hamster
hand
handball
handle
hardware
harmonica
harmony
hat
hate
hawk
head
headlight
health
heart
heat
heaven
hedge
height
helicopter
helmet
help
henhill
hip
hippopotamus
history
hockey
hole
holiday
home
honey
hood
hook
horn
horse
hose
hospital
hour
house
hurricane
hyena
ice
icicle
idea
ink
insect
instrument
Internet
invention
iron
island
jacket
jaguar
jail
jam
jar
jaw
jeans
jeep
jelly
jellyfish
jet
jewel
joke
journey
judge
judo
juice
jump
jumper
kangaroo
karate
kayak
kettle
key
keyboard
kick
kiss
kitchen
kite
kitten
knee
knife
knight
knot
lace
ladybug
lake
lamb
lamp
land
lasagna
laugh
laundry
leaf
leather
leek
leg
lemonade
leopard
letter
lettuce
library
lift
light
lightning
lily
line
lion
lip
lipstick
liquid
list
litter
lizard
loaf
lobster
lock
locket
locust
look
lotion
love
lunch
lynx
macaroni
machine
magazine
magic
magician
mail
mailbox
mailman
makeup
map
marble
mark
market
mascara
mask
match
meal
meat
mechanic
medicine
memory
men
menu
message
metal
mice
middle
milk
milkshake
mint
minute
mirror
mist
mistake
mitten
Monday
money
monkey
month
moon
morning
mosquito
motorboat
motorcycle
mountain
mouse
moustache
mouth
music
mustard
nail
name
napkin
neck
needle
nest
net
news
night
noise
noodle
nose
note
notebook
number
nut
oak
oatmeal
ocean
octopus
office
oil
olive
onion
orange
orchestra
ostrich
otter
oven
owl
ox
oxygen
oyster
packet
page
pail
pain
paint
pair
pajama
pamphlet
pan
pancake
panda
pansy
panther
pantspaper
parcel
parent
park
parrot
party
pasta
paste
pastry
patch
path
pea
peace
peanut
pear
pedestrian
pelican
pen
pencil
pepper
perfume
person
pest
pet
phone
piano
pickle
picture
pie
pig
pigeon
pillow
pilot
pimple
pin
pipe
pizza
plane
plant
plantation
plastic
plate
playground
plot
pocket
poison
police
policeman
pollution
pond
popcorn
poppy
porcupine
postage
postbox
pot
potato
poultry
powder
power
price
printer
prison
pumpkin
puppy
pyramid
queen
question
quicksand
quill
quilt
rabbit
radio
radish
raft
rail
railway
rain
rainbow
raincoat
rainstorm
rake
rat
ravioli
ray
recorder
rectangle
refrigerator
reindeer
relatives
restaurant
reward
rhinoceros
rice
riddle
ring
river
road
roast
rock
roll
roof
room
rooster
rose
rowboat
rubber
sack
sail
sailboat
sailor
salad
salmon
salt
sand
sandwich
sardine
sauce
sausage
saw
saxophone
scarecrow
scarf
school
scissors
scooter
scorpion
screw
screwdriver
sea
seagull
seal
seaplane
seashore
season
seat
second
seed
sentence
servant
shade
shadow
shallot
shampoo
shark
shears
sheep
sheet
shelf
shell
shield
ship
shirt
shoe
shoemaker
shop
shorts
shoulder
shovel
show
side
sidewalk
sign
signature
silk
silver
singer
sink
sister
skin
skirt
sky
sled
slippers
slope
smoke
snail
snake
sneeze
snow
snowflake
snowman
soap
soccer
sock
sofa
softball
soldier
son
song
sound
soup
soybean
space
spade
spaghetti
spark
sparrow
spear
speedboatspider
spike
spinach
sponge
spoon
spot
sprout
spy
square
squash
squid
squirrel
stage
staircase
stamp
star
station
steam
steel
stem
step
stew
stick
stitch
stinger
stomach
stone
stool
stopsign
stopwatch
store
storm
story
stove
stranger
straw
stream
string
submarine
sugar
suit
summer
sun
sunshine
sunflower
supermarket
surfboard
surname
surprise
sushi
swallow
swamp
swan
sweater
sweatshirt
sweets
swing
switch
sword
swordfish
syrup
table
tabletop
tadpole
tail
target
tax
taxi
tea
teacher
team
teeth
television
tennis
tent
textbook
theater
thistle
thought
thread
throat
throne
thumb
thunder
thunderstorm
ticket
tie
tiger
tile
time
tire
toad
toast
toe
toilet
tomato
tongue
tooth
toothbrush
toothpaste
top
tornado
tortoise
tower
town
toy
tractor
traffic
trail
train
transport
tray
tree
triangle
trick
trip
trombone
trouble
trousers
truck
trumpet
trunk
t-shirt
tub
tuba
tugboat
tulip
tuna
tune
Turkey
turnip
turtle
TV
twig
twilight
twine
umbrella
valley
van
vase
vegetable
veil
vein
vessel
vest
violin
volcano
volleyball
vulture
wall
wallaby
walrus
washer
wasp
waste
watch
watchmaker
water
waterfall
wave
wax
weapon
weasel
weather
wedge
whale
wheel
whip
whistle
wilderness
willow
wind
wind chime
window
windscreen
wing
winter
wire
wish
witch
wolf
woman
wood
wool
word
workshop
worm
wound
wren
wrench
wrinkles
wrist
xylophone
yacht
yak
yard
yogurt
zebra
zipper
zoo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment