2013-06-19 45 views

回答

1

您可以使用畫布的context.globalCompositeOperation覆蓋文字與圖像。

然後,您可以通過對圖像的x偏移進行動畫處理來獲得所需的運動效果。

此代碼將在畫布上繪製文本,然後用圖像覆蓋只是文本

// first draw the text on the canvas 
     ctx.beginPath(); 
     ctx.font="144pt Verdana"; 
     ctx.fillText("See",30,200); 
     ctx.fill(); 


     // use compositing to draw the background image 
     // only where the text has been drawn 
     ctx.beginPath(); 
     ctx.globalCompositeOperation="source-in"; 
     ctx.drawImage(img,-x,0); 

當然,你會想用你自己的文字字體,背景圖像和動畫模式風格化。

這裏是代碼和一個小提琴:http://jsfiddle.net/m1erickson/MrVJB/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ padding:20px; } 
    canvas{border:1px solid red; position:absolute} 
</style> 

<script> 
$(function(){ 


    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 

    var xOffset=100; // image offset 
    var fps=60; 

    var img=document.createElement("img"); 
    img.onload=function(){ 
     animate(); 
    } 
    img.src="http://images4.fanpop.com/image/photos/23400000/water-water-23444632-2048-1277.jpg"; 

    function draw(x){ 

      ctx.save(); 
      ctx.beginPath(); 

      // put text on canvas 
      ctx.font="144pt Verdana"; 
      ctx.fillText("See",30,200); 
      ctx.fill(); 
      ctx.beginPath(); 

      // use compositing to draw the background image 
      // only where the text has been drawn 
      ctx.globalCompositeOperation="source-in"; 
      ctx.drawImage(img,-x,0); 
      ctx.restore(); 
    } 


     function animate() { 

      // change the background image offset 
      xOffset+=3; 
      if(xOffset>=img.width){xOffset=0;} 

      // draw the text and background image 
      draw(xOffset); 

      // request another frame using fps intervals 
      setTimeout(function() { 
       requestAnimationFrame(animate); 
       // Drawing code goes here 
      }, 1000/fps); 
     } 


}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=400 height=300></canvas> 
</body> 
</html> 
+0

哇!做得好!這是一個非常全面的答案! – v2p

0

我在這裏看到的,例如該解決方案:

您需要創建圖像,其中的字母會透明。使用位置,你還可以在這個圖像下面設置jQuery動畫,其中對象(在這個例子中是另一個圖像)向右和向後循環。

這應該會幫助你開始。

+0

它是簡單的,但不是萬能的解決方案。如果您檢查站點代碼,您將看到使用canvas + mootools腳本。 – v2p

+0

當你是程序員時,你總是可以找到多個問題的解決方案。我只是向你展示我的願景。我無法提供完整的解決方案。也許如果我找到更多的時間,我會告訴你我的答案是什麼意思。 – WooCaSh