An Introduction to Creating Shapes With Code
I am new to HTML Canvas and SVG coding. I have chosen to include a couple of easy examples I came across, tried and edited. These have been linked later on in the post to show how they perform in a real time browser experience. In the future I hope to make another blog post showing my improvements. For now I have included some nice shapes I edited myself by adapting code taken from W3Schools.
<body> <svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="teal" stroke-width="4" fill="pink" /> </svg> </body>
The piece of code shown above is for a pink circle with a teal stroke. This is easy to spot in the third line of code where the dimensions are clearly specified, followed by colour definitions. Please click on the SVG Circle link in the below list to see this run in a browser.
Links to Experiments
Browser Compatibility
<body>
<canvas id="myCanvas" width="200" height="100" style="border:5px dotted purple"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "teal");
grd.addColorStop(1, "pink");
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
ctx.font = "30px Script";
ctx.fillStyle = "White";
ctx.fillText("Hello World", 10, 50);
</script>
</body>
If we look at the code from the Canvas Text file, we can see that I have chosen to use the ‘Script’ font type. This is particularly interesting to look at as a classic example of browser compatibility and is something to always take into consideration when creating text. In Google Chrome the script tag is not recognised and is displayed as a serif typeface, whereas if in Firefox the typeface is in the script style as expected.
Here is the image in Chrome:
Again in Firefox:
Conclusion
It was really interesting and enjoyable to try my hand at making shapes using pure code as I have never tried this before. Admittedly, these test designs are very unattractive and I have not taken any design principles into consideration because I wanted to try a range of things just to see if it worked. For example, in my Canvas Gradient example the purple line is dashed but the Canvas Line example uses a purple dotted line. These would only be aesthetically pleasing in certain designs, nevertheless they show it can be done.
Bibliography
W3schools.com. (2017). SVG Tutorial. [online] Available at: https://www.w3schools.com/graphics/svg_intro.asp [Accessed 26 Sep. 2017].

