Skip to content

Instantly share code, notes, and snippets.

@tomshanley
Last active February 10, 2020 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomshanley/10bafe67a43c7ad6911a808b06671616 to your computer and use it in GitHub Desktop.
Save tomshanley/10bafe67a43c7ad6911a808b06671616 to your computer and use it in GitHub Desktop.
matrix inside circle
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
margin: 50;
}
circle {
fill: none;
stroke: black;
stroke-width: 2px;
}
rect {
stroke: black;
stroke-width: 1px;
}
</style>
</head>
<body>
<div id="chart"></div>
<div id="count"></div>
<script>
console.clear()
let radius = 200
let diameter = radius * 2
let margin = 20
let squareWidth = 30
let n = Math.floor(diameter / squareWidth)
let offset = (diameter - (n * squareWidth)) / 2
let width = diameter
let height = width
let numberOfSquaresInsideCircle = 0
// let percent = 40
let svg = d3.select("#chart").append("svg")
.attr("width", width + (margin * 2))
.attr("height", height + (margin * 2))
let g = svg.append("g")
.attr("transform", "translate(" + margin + ", " + margin + ")")
let circle = g.append("circle")
.attr("cx", radius)
.attr("cy", radius)
.attr("r", radius)
.style("fill", "grey")
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
let x = (j * squareWidth) + offset
let y = (i * squareWidth) + offset
if(isSquareOutsideCircle(x, y, squareWidth, radius)) {
} else {
numberOfSquaresInsideCircle = numberOfSquaresInsideCircle + 1
g.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", squareWidth)
.attr("height", squareWidth)
.style("fill", "white")
.attr("id", "cell-" + i + "-" + j)
}
}
}
/*let squares = d3.selectAll("rect")
.style("fill", function(d, i){
return ((numberOfSquaresInsideCircle - i)/numberOfSquaresInsideCircle) * 100 < percent
? "orange"
: "white"
})*/
d3.select("#count")
.text(numberOfSquaresInsideCircle)
function isSquareOutsideCircle(squareX, squareY, squareW, circleR) {
if (isPointOutsideCircle(squareX, squareY, circleR)) {
return true
} else if (isPointOutsideCircle((squareX + squareW), squareY, circleR)) {
return true
} else if (isPointOutsideCircle(squareX, (squareY + squareW), circleR)) {
return true
} else if (isPointOutsideCircle((squareX + squareW), (squareY + squareW), circleR)) {
return true
} else {
return false
}
}
function isPointOutsideCircle(x, y, r) {
return hypothenuese(Math.abs(r - x), Math.abs(r - y)) > r ? true : false
}
function hypothenuese(side1, side2) {
return Math.sqrt((side1 * side1) + (side2 * side2))
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment