Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add Bitmap Images to SVG

Add Bitmap Images

https://i.imgur.com/hMRfaDm.png

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

https://i.imgur.com/GNcg1OJ.png

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.

https://i.imgur.com/8G6OucI.png

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

https://i.imgur.com/P8m4IUK.png

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
You can’t perform that action at this time.