SVG Images Made Easy

Programmer

Well, at least made easier. IMHO, svgs are not easy to understand. svg is a type of image for websites. svg stands for scalable vector graphics, whatever that means.

The important part is that you can manipulate these images in real time. This can also be difficult – it was for me for a long time. It’s possible to alter other types of images in real time. However, svg is what most people use. Canvas is an alternative to svg. But in my opinion, it’s not any easier to understand.

The simplest way to put an svg image on your website is to reference it with the img html tag. But that doesn’t allow you to manipulate it. If instead, you copy the svg image into your html page and make it inline svg, you can manipulate it. Keep reading and I’ll explain how that can be done fairly easily.


An svg image is a text file of commands to draw the image. You can open it with a text editor like Notepad++. This file looks similar to html. It starts with <svg> and ends with </svg>. Actually there may be some code before <svg>. To place your svg image inline, decide where you want it in your html and pasted everything from <svg> to </svg>. Do not include anything before <svg> (or after </svg>). It is not needed or even wanted in some cases in the inline version.

Now that you’ve pasted in those several lines of svg code, save your html file and open it in a browser. Voila, there’s your svg image on the screen. Hint: I find that it helps me immensely if I put comments around the svg. I put <!--SVG--> before the svg and <!--End SVG--> after it.

Now, to the fun part – manipulating the image.


I wanted to take a map of the USA and color each state based on certain criteria. OK, so I wanted to color each state depending on who won during a presidential election. I did this a couple of election cycles ago. It was hard work. Each time, I changed the svg file manually, then I opened it in my picture editor. I made a screen copy and saved that as a png image. Then I referenced that on an img tag in my html page.

Recently, I thought that perhaps I might want to be able to do the same sort of thing at some point in the future. So, I wrote some javascript to simplify that process. I’ve placed that javascript in xg_graph.js and uploaded it to the internet. I tried to make it as simple as possible, so that you don’t need to know much about coding.

You can read about the details of how to use that code at Really Useful Javascript Graphs. I’ll discuss the basics here.

I used the USA svg map from Wikimedia. The particular svg map I used is free to use, no attribution needed. Some svgs are free to use, but require three attributions, plus a brand logo. I think three attributions is asking a little much. But then again, I don’t need that particular svg image yet. Others svg are not free.

You can create your own svg, maybe, using Inkscape or Adobe Illustrator or maybe something else. I can’t draw, so that’s out. And probably the svg will be easier to manipulate if you use one that somebody else has created and gone to the trouble of identifying separate parts of the image.


An svg file consists of the svg or multiple nested svg. Within an svg, you can have a group (g) tag. This groups elements together. If you don’t have <g>…</g> tags, you will probably want to add them, at least one set. Just place <g> at the top at the end of <svg…> and </g> at the bottom before </svg> if you don’t know where to put them. Some of my javascript routines rely on the group tag. There are also shape tags – path, circle, eclipse, line, polyline, polygon, and rect (for rectangle). And that’s pretty much all you need to worry about: svg tag, group tag, and shape tags.


<path class="co" …><title>Colorado</title></path> is the shape for Colorado (CO). It’s identified by both the title and the class. Luckily, the shapes were identified, so that I didn’t have to figure that out.

However, my routines rely on tags being identified by ids. The Wikimedia file doesn’t have ids. But that’s easily resolved. I just add ids to the svg, group, and paths. In this case, I modified the Colorado path to be <path id="svg_co" class="co" …><title>Colorado</title></path>.

Now that my tags have id’s, I can call my xg_svg_modify routine to modify any attribute – class, bgcolor (background color), transparency, title, or text. Text can get complicated, so I manipulate title instead.

You can also modify the size of the svg. And that’s mainly what I use this routine for. It’s more complicated to change the size of an svg than just altering the width and height attributes. It took me a day or two to understand what people on the web were trying to tell me. And even then, I didn’t want to do it manually. So, a routine.


Back to politics. When I find out who won, I can call my x_who_won routine to assign the correct background color to a state shape. Yes, that’s easy enough to do manually when only two people are in the race. But what about a presidential primary when there are 16? And what about election night at 2am, when you’re waiting for the results to come in and you’re way too tired to think straight. When you find out the correct color, you can call xg_svg_modify to update it.


That’s great! But, I want to work with the svg as a whole, rather than one shape at a time. First I need to know the attributes of each shape. So, I call xg_svg_group_init. This gathers the attributes of all shapes in a group. It gathers those attributes into arrays. Arrays can be difficult to work with in javascript. But they were necessary in this case. And, I tried to keep them simple.

You will need to know the index of the array for a certain shape in order to update its attributes: co_index=xg_svg_shape_id_array.indexOf('svg_co'). This returns the index for the Colorado shape in the array. co_bgcolor=xg_svg_shape_bgcolor_array[co_index] returns the background color for Colorado. To update the background color to blue, xg_svg_shape_bgcolor_array_update[co_index]='blue'. You may also want to update the titles by appending the scores. xg_svg_shape_title_array_update[co_index]='CO 55 45'. Then call xg_svg_shapes_update to update the svg.


Maybe you’re not interested in politics. Maybe you just want to randomly color each state. My routine x_color_random_array_init creates the array x_color_random_array. After calling x_color_random_array_init, call xg_svg_shapes_update_bgcolors(x_color_random_array). Then call xg_svg_shapes_update to update the svg.

Website Color – Contrast, Primary, Random

artists pallette

Contrast

If the background of an element is dark, you want a light (typically white) text. If it’s light, you want a dark (typically black) text. But what’s dark and what’s light? Technically speaking, light colors are those whose red, green, and blue components are greater then hex 7f (decimal 127). However, our eyes are tricky creatures, and that doesn’t always work. Instead, you need to know the lightness component. You can convert the color to hsl (hue, saturation, light), but that’s rather involved. There’s also a one line if statement I found somewhere on the web which will do the trick instead.

if(((red_component*299)+(green_component*587)+(blue_component*114))/1000>128){contrast=’black’}else{contrast=’white’}

Of course, first you have to get or know the background color of the element. Then you have to convert it from whatever color system it was specified in to rgb. The color system could have been hex, rgb, or an official color name. It could have been a few other color systems. If it is, you’ll need to deal with that. Otherwise, see my functions below to help with this.

Primary Colors

What are the primary colors? Google this and you’ll typically get primary, secondary, and tertiary color names. Some people think of primary colors as the colors of a rainbow. Others think of it as the colors in an 8-crayon box.

My list of primary colors start with those where the hex red, green, and blue values are 00 or FF. This gives us Black, Red, Yellow, Green, Aqua/Cyan, Blue, Magenta/Fuschia, and White. Then I add in those colors where one or more of the values are 7F, for a total of 15 colors.

Random Colors

A Random Color is easy enough to calculate. Some people take a random value for Red (between 0 and 255), one for green, and one for blue. I just take a random number somewhere between the 0 and the maximum number of possible colors.

In Javascript, this is ‘#’+Math.floor(Math.random()*16777215).toString(16).padStart(6,’0’); I may have missed one color at the top-most value, don’t know, don’t really care. toString converts to hex, padStart adds leading zeros, if any are missing.

The real trick, is how to you generate an array of random colors, without any duplicates? What does duplicate mean? I can’t tell the difference between my wife’s navy blue socks and her black ones. I mean they should be labeled. She can. So, duplicate is a matter of how close to another color is too close? I suppose hsl would work better for this. However, I just define it as the red, green, and blue each being within 16 of the red, green, blue of another color. If that doesn’t work for you, you can call my routine passing a different value for tooclose. You’ll probably want to pass a value > 16, like 32.

I also allow you to not accept grey, black, or white values in your array. The array can contain 1000 values. However, if you disallow grey, black, or white, it may contain slightly less than 1000 values. It may also contain slightly less than 1000 values due to dups. I figured 900+ values should be sufficient for most applications.

x_press javascript functions

If you need to add some basic javascript functions to your website to deal with colors, check out my free javascript library. It’s designed to make your website more expressive. And it’s easy to use, even if you don’t know much about javascript.

 

x=x_color(elementID,foreback) will return the foreground or background color of the element. Foreback can be ‘text’,’foreground’, ‘fore’, ‘fg’ for foreground. Foreback can be ‘background’,’back’, ‘bg’ for background. Any other value will return the background color.
x=x_color_shift(rgb,redshift,greenshift,blueshift) will shift the color. Use positive value for shift for lighter, negative for darker. Specifying 16 or -16 will go slightly lighter or darker.
x_color_primary_array contains primary, secondary, and tertiary colors.x_color_primary_names_array contains the names. x_color_primary_n_array and … names array contain primary colors in sorted order where number of colors is n and n=5,8,15. Brown is actually a red-violet shade, so not included.
x_color_blackx_color_white – black and white, but you can change them to whatever you use for black and white. I was going to set x_color_text and x_color_background to document.body.style.text and document.body.style.backgroundColor, but these would be set in x_press_init. And x_press_init is usually called in <head>. And document.body.style…. is in head. You would need to set your own variables for these in a script after <body>. You might also want to set a variable for document.body.style.borderColor. You can of course you document.body.style…. The only reason for corresponding variables, would be if you can’t recall document.body.style….
x=x_color_convert(fromcolor,tocolor_type) will convert color from one type to another. From type is name, hex, or rgb and is derived from fromcolor. tocolor_type needs to be specified if rgb, otherwise it defaults to hex. tocolor is the returned value.
x=x_color_random_array_init(allowgray,allowblack,allowwhite,tooclose) loads an array of up to 1000 random colors. By default, gray, black, and white are not allowed. The array may contain slightly less than 1000 colors, especially if you disallow gray, black, and white. Also, duplicate colors are not included in the array. Duplicate in this case means that the color is too close to another color in the array. tooclose defaults to 16, meaning the red, green, and blue values are within 16 of each other. You can change tooclose. I suggest increasing it, like to 32. Increasing tooclose raises the chance that the array will contain less than 1000 elements, but you’ll probably still have plenty.
x=x_color_contrast(color) returns a contrasting color. Typically, you have a background color and you want to contrast the (foreground / text) color.
x=x_color_contrast_per_background(x_el,settextcolor=false,setbordercolor=false) returns a contrasting color based on an element’s background. Optionally sets text and/or border colors. This works for elements. It does not work for document.body. To set, document.body.style.color=x_color_contrast(document.body.style.backgroundColor)

Add Animated Cards to your Website

Programmer

I should have added the word Easily to the title of those post. Alas, I didn’t.

When writing my fantasy series, The Wizard without a Wand, I had trouble keeping track of all the characters. First, there’s the tensome – ten Wizard School students who hang out together. They even share the same dorm room – the school calls their dorms hotels. Even so, we all know they’re just dorms, not hotels. Then there are parents, teachers, the Principal, etc.

I figured, if I had trouble keeping them straight, my readers might also. So I added a cast of characters at the end of each of the ten books in that series. I didn’t intend for there to be 10 books. I didn’t even intend for it to be a series. That just happened.

Anyway, when I added that series to my website, I decided to add the cast of characters to the website also. Then I decided to get fancy, and put each of the Tensome on a card on the website. I wanted the card to be animated, so that when a user clicked it, it would turn over and show the user more information.

In order to have the card turn over, I animated it. I created my own animation routines in javascript. These are free and easy to use, provided you can understand javascript just a little bit. And provided you can add javascript to your website. I call this library of routines xa_animate. It goes along with my x_press javascript library which helps make your website more expressive. These libraries are accessible at https://stubbart.com/computer_consulting/code/index.html

You can use these animated cards for playing cards, greeting cards, or business cards. You might want to use a card for each of the top people in your company on your company’s website.

Turning over the card, means rotating it. For my children’s superhero series Zuper Zero (Only three books this time, so far. Again, series was unintended.), I wanted the front of the card to slide into the sky. So, I added the Scroll method to the Rotate Method.

Then I added the Slide method (a variant of the scroll method with more options), the Fade method, and the Open Method.

In my scifi book Shalomar (no series this time), one of the main characters is named Glo-Reta. One of my favorite lines from that books is, Life wasn’t bad, living with Glo-Reta in Gariza. Anyway, I wanted the front of the card to glow as it disappeared and showed the back. So, I added the Filter method.

The Filter method is a repeat of the Fade method, however, in addition to opacity (opposite of transparency), you can apply blur, brightness, contrast, grayscale, hue-rotate, saturation, and sepia. My test picture glowed the best with brightness and contrast. Glo-Reta’s glowed the best with brightness, grayscale, and hue-rotate. I have no idea why grayscale helped. hue-rotate alters the color, so yellows become purples, or some such.

https://stubbart.com/computer_consulting/code/xa_animate.html – xa_animation documentation and examples.

https://stubbart.com/publishing_consulting/cast/wizardwithoutawand.html – Wizard without a Wand – Cast of Characters

https://stubbart.com/publishing_consulting/cast/zuperzero.html – Zuper Zero – Cast of Characters

https://stubbart.com/publishing_consulting/cast/shalomar.html – Shalomar Cast of Characters

Expressive Websites 4.0

Programmer

I have updated my expressive websites library – this time to handle Chrome’s deprecation of document.write. If you’re using document.write on your websites, please refer to my previous post. If you’re using my expressive websites library, please refer to the changes there, where everything is well documented.

x_d_w(string) was changed to x_ih(string,element). This places a string in the element you specify, overwriting any text which was previously there.

x_script_ih replaces x_script. Again, add an element as the last parameter. Similarly x_contact_ih replaces x_contact.

ih stands for innerHTML which is what the function is doing rather than document.write.

Document.Write – Don’t Use!!!

Programmer

I like the javascript web comment document.write. It places what I want, where I want it on the website. This is great for menus and other things that you’re repeating on multiple pages of your site. And Chrome just killed it! Well, they killed it in version 54 and we’re now on 77. I just now noticed it not working.

So, why didn’t I notice it until now? Well, Chrome didn’t really kill it, they just deprecated it to the point where it sometimes doesn’t work. And they’ll eventually deprecate it to the point that it won’t work at all. Why, because it can be slow.

I had most of mine sped up. Rather than having several document.write statements in a row, I created a string and then did document.write on that string. v=’xxx’;v+=’yyy’; etc. document.write(v). I even liked document.write so much that I created a shortcut function for it in my Expressive Websites Javascript Library – need to deprecate that too I guess. Or at least note that it may no longer work.

However, Chrome still thought that they were too slow. So I’m having to fix my websites. Stubbart.com, FantasticStoriesForYou .com , WeCanReverseClimateChange .com , and PrincessTigerlily.com. That’s only 4 websites, but several webpages per.

I replaced document.write with innerHTML. To do this, id an element before the <script> statement. Chrome tells me that I’m supposed to make my scripts async …. But for what I’m doing not sure that applies. Anyway this works, for now. Make sure that you don’t do something like <p><script></script></p> – place those outer paragraph tags inside the script – as part of the innerHTML. Then place a <div id=…></div> before the script.

innerHTML is elementid.innerHTML=v. So if your id is xyz, then xyz.innerHTML=v. My code still didn’t work when I forgot to close the element before the script – it doesn’t exist until you close it. Also, if I had a document.write within a script, I had to rework that, making sure that the element was created before the innerHTML statement. And innerhtml doesn’t work – the HTML must be uppercase.

When passing the id to a function, I had to use document.getElementById(x).innerHTML=v. And if I uppercased ID it didn’t work – javascript is case sensitive. Of course I knew that, but I can’t remember what somebody else decided was uppercase and what wasn’t.

Bottom line – if you’re using one of my websites and it doesn’t work – try again tomorrow. This is going to take a little bit of time.

Emojis for Books

author

Hey #writingcommunity, do you use emojis in your books? Do you use emojis to promote your 📚? Which emojis do you use 🤔 Why isn’t there an emoji for emoji?

I use various emojis on my website to denote book themes – superheroes, romance, wee people, shapeshifters, magic, families, time travel, etc. Check out both my children’s and fantasy pages to see most of these. If there’s an animal, cat, etc, in my book, I try to denote that with an emoji also. Note: I usually limit animals to dinosaurs and dragons, though the main character #protaganist in Cascadia Prime might be a relative of big foot. However, there’s no emoji for sasquatch.

When I’m looking for emojis, I look in three places: Emojipedia, Really Useful Unicode, and/or an Emoji Keyboard. Really Useful Unicode is my web library for Unicode symbols which are the predecessors of emojis. I use this library for two reasons: 1) Letters, numbers, punctuation, algebra, simple shapes – square, 𝕖𝓉ⓒ. 2) When I can’t think of how to convey an idea. For example, this library contains many symbols for #writing. ✍, 💄🤏,ණ, etc.

I sometimes use emojis in my books. However, sometimes, when I upload the book to Amazon, the emoji turns into tofu ⎕ or just doesn’t show up. This is especially true of more recent emojis. It is also often true when the emoji is made up of multiple symbols, such as my superhero emoji (because there is no superhero emoji). Emojipedia will tell you if there are multiple codes used to make up an emoji when you scroll near the bottom. So, I try to remember to double check that. Another note on this: emoji flags won’t work in Windows, at least not without my Expressive Websites javascript library.

When emojis aren’t working in my books, I have to use the picture behind the emoji. The pictures for most emoji’s are copyrighted, so I tend to use the Windows, Google, or Twitter versions. The Windows version is copyrighted, but since the emoji font is covered by my Windows copyright, the picture should be also, shouldn’t it? Anyway, I often prefer the Google or Twitter version. If I need something slightly different, I can maybe find a picture on Pixabay or WPClipArt. And I often like to take something as a starting point and modify it to make my own unique version of an emoji.