2014-09-02 112 views
0

我想(我已經完成1-3):帆布動畫剪貼蒙版路徑

  1. 抓住從頁面的圖像
  2. 它的圖像添加到畫布元素
  3. 夾到面罩
  4. 移動(動畫)圖像

我已經完成了前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, ''); 

如何從畫布上移動(動畫)剪貼蒙版以顯示剪切圖像的不同部分?

感謝您的任何想法!

回答

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(); 
} 
+0

謝謝@ markE,太棒了!但是,我正面臨着一個問題,它需要從div的背景中抓取圖像(必須做到這一點),並將其放置在畫布內以移動遮罩。我在這裏更新了小提琴:http://jsfiddle.net/07mzbat9/2/。如果你有任何想法,我將不勝感激,因爲這已經讓我困惑了幾天。謝謝!! – 2014-09-02 19:08:44

+0

這裏是我的小提琴修改爲抓住div元素的背景圖片:http://jsfiddle.net/m1erickson/56wqqmqe/祝你的項目好運! – markE 2014-09-02 19:56:07