2014-09-02 3 views
0

나는 (I 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 that awesome! 그러나, 나는 div의 배경에서 이미지를 잡아서 (이 b/c 마크 업 구조체를 가져와야 함) 캔버스 안쪽에 배치하여 마스크를 이동해야하는 문제에 직면하고 있습니다. 나는 여기에서 바이올린을 업데이트했다 : http://jsfiddle.net/07mzbat9/2/. 아이디어가 있으면 감사하게 생각합니다. 며칠 동안 저를 곤란하게 만들었습니다. 감사!! –

+0

다음은 div 요소의 배경 이미지를 잡아 내 수정 한 것입니다. http://jsfiddle.net/m1erickson/56wqqmqe/ 프로젝트에 대한 행운을 비세요! – markE