Hey there! I'm trying to create a cool spinning wheel using a canvas and JS. My wheel is supposed to have 10 segments, each saved as a .png file.
https://i.sstatic.net/glN1p.jpg
In order to achieve a "full circle", I want to draw these 10 segments in a for loop.
https://i.sstatic.net/5PqtU.png
I've been working on this code, but unfortunately, my "wheel" looks pretty messed up - I seem to be missing something.
const segmentCount = 10;
let initializeWheel = function() {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let size = $(window).width() * 0.9;
canvas.width = canvas.height = size;
ctx.fillStyle = "red"
ctx.fillRect(0, 0, size, size)
for (let segmentIndex = 0; segmentIndex < segmentCount; segmentIndex++) {
let image = new Image()
image.onload = function() {
let h = ((size / 2) / image.width) * image.height,
w = size / 2;
let x = size / 4,
y = h;
let degrees = segmentIndex * (360 / segmentCount)
ctx.save();
ctx.translate(x + w / 2, y + h / 2);
ctx.rotate(degrees * Math.PI / 180.0);
ctx.translate(-x - w / 2, -y - h / 2);
ctx.drawImage(image, x, y, w, h);
ctx.restore();
};
image.src = "https://i.sstatic.net/5PqtU.png"
}
$(canvas).appendTo(document.body)
}
initializeWheel()
canvas {
position: "absolute";
left: 0;
right: 0;
margin: "auto";
top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>