Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active October 18, 2018 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codetricity/0f71b27e0dd50f624972c6452625256b to your computer and use it in GitHub Desktop.
Save codetricity/0f71b27e0dd50f624972c6452625256b to your computer and use it in GitHub Desktop.
Add Bitmap Images to SVG

Add Bitmap Images

image

Continuation of data join lesson for Civil War

https://gist.github.com/codetricity/3f4958488fdf87b912988bfa77384661

Demo

https://codetricity.github.io/d3-maps/civilwarjoin.html

What is a Bitmap Image

  • standard graphic file that people normally use
  • jpg, png, tiff are all bitmap images
  • loss of resolution when scaling
  • edit in GIMP or Photoshop as well as most graphics programs
  • most common format

SVG needs to be edited in Illustrator or InkScape.

Apply Background Image

Download image.

https://raw.githubusercontent.com/codetricity/d3-maps/master/assets/civilwarmap.jpg

svg.append('image')
  .attr('xlink:href', 'assets/civilwarmap.jpg')
  .attr('x', '0')
  .attr('y', '0')
  .attr('width', '600')
  .attr('height', '500')
  .attr('opacity', '0.2');

download additional backgrounds

Modify Button to change background image

image

assign a variable background to the background image you created above.

  1. go to buttons event handler on.('change',...
  2. go to the if statement for selection == union
  3. add background.attr...
  4. change opacity to 1.0

Answer and example code is below the next image.

image

const buttons = d3.selectAll('input');
buttons.on('change', function(d) {
 console.log('button changed to ' + this.value);
 const selection = this.value;
 if (selection == 'union') {
   background      
     .attr('xlink:href', 'assets/union.png')
     .attr('opacity', '1.0');
   listAlliance(union);

Change Backgrounds for Both Confederate and Border

Add HTML button for all

image

handle button press event 'all'

Assume that there is a new function called, listAllStates. Pass all there alliance arrays to the new function.

} else if (selection == 'all') {
  background      
  .attr('xlink:href', 'assets/civilwarmap.jpg')
  .attr('opacity', '0.2');
  listAllStates(union, confederate, border);
}

create function listAllStates

Remove Current Text

function listAllStates(union, confederate, border) {
svg.selectAll('text').remove();

Add Column for Union

svg.append('text')
.text('Union')
.attr('x', '50')
.attr('y', '50')
.style('font-weight', 'bold');

Go Through Union Array and List Each Element

union.forEach((element, i) => {
  svg.append('text')
    .text(element)
    .attr('x', '50')
    .attr('y', i * 20 + 80);
});

Add Confederate and Border

Add Transitions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment