Canvas Animate剪贴蒙版路径

时间:2014-09-02 17:58:47

标签: javascript html5 canvas html5-canvas image-clipping

我想(我已经完成了1-3):

  1. 从页面中抓取图片
  2. 将其添加到画布元素
  3. 将图像剪辑为遮罩
  4. 围绕图像移动(动画)遮罩
  5. 我已经完成了前3个,但无法弄清楚如何移动面具..请帮忙!

    // get the canvas
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');  
    
    // get a div from the page
    var stuff = document.getElementsByName('testElem')[0];
    
    // add a class to the div
    stuff.setAttribute('class', 'pleaseWork');
    var newImage = new Image();
    
    // get the background image of the div
    var bgClass = document.getElementsByClassName('pleaseWork')[0].style.backgroundImage;
    
      var x = canvas.width / 2;
      var y = canvas.height / 2;
      var radius = 75;
      var offset = 50;  
    
      // clip the context to create a circular clipping mask
      context.save();
      context.beginPath();
      context.arc(x, y, radius, 0, 2 * Math.PI, false);
      context.clip();
    
    // on load put the image into the clipping mask
    newImage.onload = function () {
        context.drawImage(newImage,0,0);
    }
    
    // put the background image from the div into the canvas (without the url())
    newImage.src = bgClass.replace(/^url|[\(\)]/g, '');
    

    如何从画布移动(动画)剪贴蒙版以显示剪切图像的不同部分?

    感谢您的任何想法!

1 个答案:

答案 0 :(得分:0)

您可以将剪辑+绘图代码放在一个函数中,并在动画循环中调用该函数:

示例代码和演示:http://jsfiddle.net/m1erickson/07mzbat9/

绘图功能:

function draw(){

    // clear the canvas
    ctx.clearRect(0,0,cw,ch);

    // save the unclipped context
    ctx.save();

    // draw a circular path
    ctx.beginPath();
    ctx.arc(cx,cy,radius,0,PI2);
    ctx.closePath();
    ctx.stroke();

    // create a clipping path from the circular path
    // use the clipping path to restrict drawing 
    ctx.clip();
    ctx.drawImage(img,0,0);

    // restore the unclipped context (to remove clip)
    ctx.restore();
}

动画循环:

var cw=canvas.width;
var ch=canvas.height;
var cx=50;
var cy=50;
var radius=35;
var PI2=Math.PI*2;

// animate the mask across the canvas
function animate(time){
    if(cx-radius>cw || cy-radius>ch){return;}
    requestAnimationFrame(animate);
    cx+=0.2;
    cy+=0.2;
    draw();
}