如何在画布圆片中添加图像?

时间:2017-03-15 10:21:39

标签: javascript html5

我正在尝试在每片画布上创建一个带有图像的轮盘赌。到目前为止,我成功创建了一个圆圈并旋转了那个圆圈。这是一个示例代码:



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();
&#13;
#myCanvas {
  border: 1px solid #d3d3d3;
}
&#13;
<canvas id="myCanvas" width="500" height="500">
Your browser does not support the HTML5 canvas tag.
</canvas>
&#13;
&#13;
&#13;

它创建一个带切片的圆圈。现在我要做的是将图像放在这些切片中。我使用过drawImage()但它并没有达到我的目的。所以,如果有人知道任何解决方案,请亲切地回答它。我被困在这个问题上已经有4天了。

1 个答案:

答案 0 :(得分:0)

这个答案是基于这个:

  

canvas clip image in a circle

&#13;
&#13;
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;
};
&#13;
#circle {
  position: absolute;
  top: 0;
  left: 0; 
}
&#13;
<canvas id="circle" width="500" height="500"></canvas>
&#13;
&#13;
&#13;