<h2>SVGルーレットテスト002</h2>
<style>
#rSVG {
position: absolute;
left: 0px;
top: 150px;
border: 1px solid #dddddd;
}
.arrow {
position: absolute;
left: 145px;
top: 170px;
width: 10px;
height: 130px;
background: black;
transform-origin: bottom center;
transition: transform 5s ease-out;
}
button {
font-size: 18px;
}
#result {
font-size: 24px;
}
</style>
<button id="btn1" onclick="drawGraph()">描画</button>
<button id="btn1" onclick="spin()">スタート!</button>
<div class="rc">
<svg id="rSVG" width="300" height="300"></svg>
</div>
<div id="result"></div>
<div id="arrow" class="arrow" style="transform: rotate(1455deg);"></div>
<script>
function drawGraph() {
const svg = document.getElementById("rSVG");
const colors = ["#ff7777", "#77ff77", "#7777ff", "#ffff77", "#77ffff", "#ff77ff"];
drawRoulette(svg, 150, 150, 150, colors);
}
function drawRoulette(svgElement, centerX, centerY, radius, colors) {
const slices = colors.length;
for (let i = 0; i < slices; i++) {
const startAngle = (i * 360) / slices;
const endAngle = ((i + 1) * 360) / slices;
// 度 → ラジアン
const startRad = (startAngle - 90) * Math.PI / 180;
const endRad = (endAngle - 90) * Math.PI / 180;
const x1 = centerX + radius * Math.cos(startRad);
const y1 = centerY + radius * Math.sin(startRad);
const x2 = centerX + radius * Math.cos(endRad);
const y2 = centerY + radius * Math.sin(endRad);
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
const d = `
M ${centerX},${centerY}
L ${x1},${y1}
A ${radius},${radius} 0 0,1 ${x2},${y2}
Z
`;
path.setAttribute("d", d);
path.setAttribute("fill", colors[i]);
svgElement.appendChild(path);
}
}
const sectors = 6;
const anglePerSector = 180 / sectors;
let currentRotation = 0;
function spin() {
const randomNum = Math.floor(Math.random() * sectors) + 1;
const stopAngle = (randomNum - 1) * anglePerSector + anglePerSector / 2;
const extraRotation = 360 * 4;
const totalRotation = currentRotation + extraRotation + stopAngle;
currentRotation = totalRotation;
const arrow = document.getElementById("arrow");
arrow.style.transform = `rotate(${totalRotation}deg)`;
}
</script>