Created
December 21, 2014 21:27
-
-
Save geekynils/0aed71148235560d5d31 to your computer and use it in GitHub Desktop.
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
/** | |
* Koch Curve | |
* F -> F + F - F - F + F | |
* F means draw a straight line, + means turn left Pi/2 and - means turn | |
* right Pi/2. | |
* See wikipedia for more. | |
* | |
* by NilsB | |
*/ | |
import QtQuick 2.3 | |
Rectangle { | |
width: 800 | |
height: 600 | |
Canvas { | |
id: canvas | |
width: parent.width | |
height: parent.height | |
antialiasing: true | |
property int l: 3 | |
property int xPos: 20; | |
property int yPos: parent.height - 20; | |
function turnLeft(ctx) { | |
ctx.rotate(-Math.PI/2); | |
} | |
function turnRight(ctx) { | |
ctx.rotate(Math.PI/2); | |
} | |
function drawLine(ctx) { | |
ctx.lineTo(l, 0); | |
ctx.translate(l, 0); | |
} | |
function drawBasicShape(ctx) { | |
drawLine(ctx); | |
turnLeft(ctx); | |
drawLine(ctx); | |
turnRight(ctx); | |
drawLine(ctx); | |
turnRight(ctx); | |
drawLine(ctx); | |
turnLeft(ctx); | |
drawLine(ctx); | |
} | |
function rKoch(ctx, n) { | |
if (n === 1) { | |
drawBasicShape(ctx); | |
return; | |
} | |
var m = n - 1; | |
rKoch(ctx, m); | |
turnLeft(ctx); | |
rKoch(ctx, m); | |
turnRight(ctx); | |
rKoch(ctx, m); | |
turnRight(ctx); | |
rKoch(ctx, m); | |
turnLeft(ctx); | |
rKoch(ctx, m); | |
} | |
function kochCurve(ctx, nIterations) { | |
ctx.lineWidth = 2; | |
ctx.strokeStyle = "red"; | |
ctx.beginPath(); | |
ctx.translate(xPos, yPos); | |
ctx.moveTo(0, 0); | |
rKoch(ctx, nIterations); | |
ctx.stroke(); | |
} | |
onPaint: { | |
var ctx = canvas.getContext('2d'); | |
kochCurve(ctx, 5); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment