Created
December 1, 2014 16:51
-
-
Save Ernir/a09a4581d164b9100990 to your computer and use it in GitHub Desktop.
Jólatré í JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas id="theCanvas" width="200" height="250" style="border: 1px solid black;"> | |
Sorry, but your browser does not support the HTML5 canvas tag. | |
</canvas> | |
<script> | |
"use strict"; | |
function drawEverything() { // This is not recyclable code. | |
var canvas = document.getElementById("theCanvas"); | |
var ctx = canvas.getContext("2d"); | |
var halfBaseWidth = 50; // Partial parametrization | |
var branchHeight = 20; | |
var branchDepth = 10; | |
var cx = canvas.width / 2; | |
var x = cx + halfBaseWidth; | |
var y = canvas.height - branchHeight; | |
var odd = true; // The first branch we draw is odd | |
ctx.beginPath(); // Begin the tree path | |
ctx.moveTo(x, y); | |
while (x > cx) { // Up the right side of the tree | |
if (odd) { | |
x -= branchDepth; | |
y -= branchHeight; | |
} else { | |
x += branchDepth / 2; | |
} | |
ctx.lineTo(x, y); | |
odd = !odd; | |
} | |
var starY = y; // We'll need this later | |
while (y < canvas.height - branchHeight) { // Down the left side | |
if (odd) { | |
x -= branchDepth; | |
y += branchHeight; | |
} else { | |
x += branchDepth / 2; | |
} | |
ctx.lineTo(x, y); | |
odd = !odd; | |
} | |
ctx.fillStyle = "green"; | |
ctx.closePath(); | |
ctx.fill(); // End tree path | |
ctx.beginPath(); // Begin the star path | |
var realcx = (x + cx + halfBaseWidth) / 2; | |
var starRadius = branchHeight / 2; | |
ctx.fillStyle = "yellow"; | |
// The star is a circle. Stars are circles. | |
ctx.arc(realcx, starY, starRadius, 0, Math.PI * 2); | |
ctx.fill(); | |
ctx.closePath(); // End the star path | |
ctx.beginPath(); // Begin the stem path | |
ctx.fillStyle = "brown"; | |
var halfStemThickness = halfBaseWidth/3; | |
var stemHeight = branchHeight*(3/4); | |
ctx.moveTo(realcx - halfStemThickness,y); | |
ctx.lineTo(realcx - halfStemThickness,y+stemHeight); | |
ctx.lineTo(realcx + halfStemThickness,y+stemHeight); | |
ctx.lineTo(realcx + halfStemThickness,y); | |
ctx.fill(); | |
ctx.closePath(); // End the stem path | |
} | |
drawEverything(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment