コッホ曲線完成
<!DOCTYPE html> <html lang="ja"> <head> <title>コッホ曲線を描く</title> <meta charset="UTF-8"> <style> #canvas { background: #FFFFFF; } </style> </head> <body> <canvas id="canvas" width="640" height="480"></canvas> <input type="button" value="start" onclick="drawLoopSquare();"/> <script> function drawLoopSquare() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext('2d'); var width = canvas.width; var height = canvas.height; var x = 1.0; var y = 0.0; var plusX = 0.0; var plusY = 0.0; var size = 2; //描画フロー function render() { /*1番目の時*/ if(rand() == 1) { plusX = 0.5 * x + (Math.sqrt(3) / 6.0) * y; plusY = (Math.sqrt(3) / 6.0) * x - 0.5 * y; x = plusX; y = plusY; console.log("x:", x, "y:", y); ctx.beginPath(); ctx.fillRect(x * 640, 450 - (y * 480), size, size); /*2番目の時*/ } else if(rand() == 2) { plusX = 0.5 * x - (Math.sqrt(3) / 6.0) * y + 0.5; plusY = -(Math.sqrt(3) / 6.0) * x - 0.5 * y + Math.sqrt(3) / 6.0; x = plusX; y = plusY; console.log("x:", x, "y:", y); ctx.beginPath(); ctx.fillRect(x * 640, 450 - (y * 480), size, size); } } for(var i = 0;i < 6000;i++) { render(); } /*ランダム関数*/ function rand(){ var r; r = Math.floor(Math.random() * 2) + 1; return r; console.log("random:", r); } } drawLoopSquare(); </script> </body> </html>
実行結果:
書き方変かもしれないけど初心者だしゆるして