裁剪图像像饼图

skm*_*asq 8 javascript canvas raphael html5-canvas

我想将图像裁剪为另一个图像,如饼图,以创建加载动画.我正在考虑使用raphaeljs,但无法找到有关饼图样式的图像裁剪的任何信息.

以下是示例图片:

开始状态:

开始状态

结束状态:

结束状态

应该是什么样的:

应该是什么样的

小智 7

只需在图像顶部绘制一个半透明的填充弧(将alpha值调整为令人愉悦的):

var ctx = document.querySelector("canvas").getContext("2d"),
    img = new Image;

img.onload = draw;
img.src = "http://i.imgur.com/hQ5Pljv.png";

function draw(){

  var cx = 157, cy = 159, r = 150,
      pst = 0,
      ang = Math.PI * 2 * (pst/100),
      dlt = 2;
  
  // animate the following part
  (function loop() {
    ctx.drawImage(img, 0, 0);
  
    ctx.beginPath();
    ctx.moveTo(cx, cy);
    ctx.arc(cx, cy, r, 0, ang);
    ctx.fillStyle = "rgba(0,0,0,0.33)";  // adjust alpha here
    ctx.fill();

    pst += dlt;
    if (pst <= 0 || pst >= 100) dlt = -dlt;
    ang = Math.PI * 2 * (pst/100);

    requestAnimationFrame(loop)
  })()
}
Run Code Online (Sandbox Code Playgroud)
<canvas width=320 height=320></canvas>
Run Code Online (Sandbox Code Playgroud)

方法二 - 合成

使用两个步骤剪切上面的相同弧以使用图像:

  • 绘制弧线,这将是复合数据
  • 改变补偿.mode to source-atop- next drawing取代绘制的弧
  • 绘制二次图像
  • 改变补偿.模式到destination-atop- 下一个绘图将填充所有非像素
  • 绘制主图像

演示:

var ctx = document.querySelector("canvas").getContext("2d"),
    img1 = new Image, img2 = new Image, cnt=2;

img1.onload = img2.onload = loader;
img1.src = "http://i.imgur.com/hQ5Pljv.png";
img2.src = "http://i.imgur.com/k70j3qp.jpg";

function loader(){if (!--cnt) draw()};                      
function draw(){
  var cx = 157, cy = 159, r = 150,
      pst = 0, ang = Math.PI * 2 * (pst/100), dlt = 2;
  
  // animate the following part
  (function loop() {
    ctx.clearRect(0, 0, 320, 320);   // clear canvas, or set last comp mode to "copy"
    
    // first arc
    ctx.beginPath();
    ctx.moveTo(cx, cy);
    ctx.arc(cx, cy, r, 0, ang);
    ctx.fill();       // this will be comp. basis for the next steps

    // comp mode secondary image
    ctx.globalCompositeOperation = "source-atop";      // replaces filled arc
    ctx.drawImage(img2, 0, 0);

    // comp mode main image
    ctx.globalCompositeOperation = "destination-atop"; // fills all non-pixels
    ctx.drawImage(img1, 0, 0);

    pst += dlt; if (pst <= 0 || pst >= 100) dlt = -dlt; ang = Math.PI * 2 * (pst/100);
    ctx.globalCompositeOperation = "source-over";  // reset comp. mode
    requestAnimationFrame(loop)
  })()
}
Run Code Online (Sandbox Code Playgroud)
<canvas width=320 height=320></canvas>
Run Code Online (Sandbox Code Playgroud)