Skip to content

Instantly share code, notes, and snippets.

@Tacumi
Created May 19, 2020 00:22
Show Gist options
  • Save Tacumi/7bbad87db1122e957c49e7ec1dca540d to your computer and use it in GitHub Desktop.
Save Tacumi/7bbad87db1122e957c49e7ec1dca540d to your computer and use it in GitHub Desktop.
JSでおえかき(canvasを使いたかった)
<!DOCTYPE html>
<html>
<head>
<title>canvas tutorial</title>
<style>
#canvas {
background: #ccc;
}
</style>
<script type="text/javascript">
const BRANCH = 4;
const LEAST_ANGLE_BRANCH = (180/BRANCH)/3;
const COLOR_LIST = ["black", "white", "green" ,"brue", "red", "yellow", "orange", "gray"];
function initialize() {
let canvas = document.getElementById("canvas");
let initial_x = 320, initial_y = 480;
let r = 120;
let theta = 90;
let target_x = initial_x -
r * Math.cos(theta * (Math.PI / 180));
let target_y = initial_y -
r * Math.sin(theta * (Math.PI / 180));
let context = canvas.getContext('2d');
drawLine(context, initial_x, initial_y,
target_x, target_y);
recursiveDrawTree(context, target_x, target_y, r, 0);
}
function recursiveDrawTree(ctx, x, y, r, depth){
let theta = 0;
if(depth > 6) return;
for(let i=0; i < BRANCH ; i++){
theta += Math.random()*(180/BRANCH)+LEAST_ANGLE_BRANCH;
let to_x = x -
r * Math.cos(theta * (Math.PI / 180));
let to_y = y -
r * Math.sin(theta * (Math.PI / 180));
drawLine(ctx, x, y,
to_x, to_y, depth);
recursiveDrawTree(ctx, to_x, to_y, r*0.6, depth+1);
}
}
function drawLine(ctx, from_x,from_y, to_x,to_y, depth){
const current_color = depth % COLOR_LIST.length;
ctx.strokeStyle = COLOR_LIST[current_color];
console.log(ctx.fillStyle);
ctx.beginPath();
ctx.moveTo(from_x, from_y);
ctx.lineTo(to_x, to_y);
ctx.closePath();
ctx.stroke();
}
</script>
</head>
<body onLoad="initialize()">
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment