2

I am trying to create a roulette with image on each slice of canvas. So far I am successful in creating a circle and in rotating that circle. Here's a sample code:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var radius = 100;

for (var i = 0; i < 8; i++) {
  ctx.beginPath();
  ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ', 95, 180)';
  // We have to add this, otherwise, it will fill the minimum area needed to fill the arc
  ctx.moveTo(300, 300);
  ctx.arc(300, 300, radius, i * Math.PI / 4, (i + 1) * ((Math.PI / 4)), false);
  ctx.closePath();
  ctx.fill();
}

ctx.stroke();
#myCanvas {
  border: 1px solid #d3d3d3;
}
<canvas id="myCanvas" width="500" height="500">
Your browser does not support the HTML5 canvas tag.
</canvas>

It creates a circle with slices. Now what I am trying to do is to put images in those slices. I have used drawImage() but it didn't fulfill my purpose. So please if someone knows any solution kindly answer it. Its been 4 days that I am stuck in this issue.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Usman
  • 55
  • 1
  • 8

1 Answers1

0

This answer is based off of this:

canvas clip image in a circle

var canvas = document.getElementById('circle'),
    ctx = canvas.getContext('2d'),
    offsetX = -116,
    offsetY = 8,
    centerX = 228,
    centerY = 100,
    radius = 100,
    slices = 8;

let slice = 0;
ctx.font = "20px Arial";

var imageObj = new Image();
imageObj.onload = function() {
  setInterval(drawSlice, 250);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

function drawSlice() {
  var cx = centerX + offsetX,
      cy = centerY + offsetY,
      angleStart = (2 * Math.PI) * (slice / slices),
      angleEnd = (2 * Math.PI) * (((slice + 1) % slices) / slices);
      
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText("Current slice: " + (slice + 1) + '/' + slices, centerX, cy);
  
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(cx, cy);
  ctx.arc(cx, cy, radius, angleStart, angleEnd, false);
  ctx.lineTo(cx, cy);
  ctx.clip();
  ctx.drawImage(imageObj, offsetX, offsetY);
  
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 4;
  ctx.beginPath();
  ctx.moveTo(cx, cy);
  ctx.arc(cx, cy, radius, angleStart, angleEnd, false);
  ctx.lineTo(cx, cy);
  ctx.stroke();
  ctx.restore();
  
  slice = (slice + 1) % slices;
};
#circle {
  position: absolute;
  top: 0;
  left: 0; 
}
<canvas id="circle" width="500" height="500"></canvas>
Community
  • 1
  • 1
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • I appreciate your effort sir but the thing is I want to add that image in a slice as in the above code there are 8 slices so is there any way to do this? – Usman Mar 15 '17 at 10:53
  • Thanks @Mr. Polywhirl for your help :) – Usman Mar 17 '17 at 13:24