2014-01-15 40 views
0

我有一個像http://s18.postimg.org/93lnr5sdl/img.png的圖像,需要在畫布中畫5秒。JavaScript/canvas - 如何從源圖像中繪製圖像?

有沒有任何選擇如何做到這一點?逐行(我知道應該繪製這些行的順序)。

我知道它不會是st。像

img = '...'; 
draw(img, 5000) 

但我需要一個建議,什麼搜索。

我的想法是讓這個圖像位於白色背景的空白元素上,並逐個生成寬度:0(所以不畫線,但是顯示隱藏在白色定位元素下的每一行 但是,有與曲線或線,太靠近(例如後窗)有問題。

任何想法? 感謝。

+0

您可能想要使用基於矢量的圖像並逐行在畫布上繪製它。重新繪製現有的PNG是「困難的」(大量手動工作)。你有沒有源圖形(在它被PNGed之前)? –

回答

1

我認爲要動畫汽車爲繪圖如果藝術家正在勾畫每一條線

你可以這樣做,但它會ta對你來說相當有點工作。

首先,獲取html畫布繪製命令來繪製線條藝術的每個路徑。

這部分其實很簡單。

  • 使用Adobe Illustrator中的跟蹤工具來獲取線條圖中每條線的路徑。

  • 保存路徑.SVG

  • 使用像canvg或邁克·斯旺森的AI一個工具到.SVG轉換成HTML,畫布繪製命令。

  • 清理生成的畫布命令(轉換工具不完美)。由於您的圖形是單色的,因此可以消除轉換工具添加的許多重複樣式更改。

我爲您的示例圖像做了這個。

  • 圖像的svg版本在這些路徑上有16個路徑和135個錨點。

  • 圖像的畫布版本具有336個由直線和貝塞爾曲線組成的繪圖命令。

  • 畫布版本可以通過半冗餘的風格變化進行簡化(我沒有做到這一點)

結果 - 這是你畫線的畫布版本:

http://jsfiddle.net/m1erickson/aaSCB/

enter image description here

現在困難的部分:EAC動畫的繪製h線和貝塞爾曲線。

您現在有100(+ - )行和曲線可以用動畫繪製。

要做到這一點,您需要繪製每一行上的每個點,以便您可以在這些線條點上進行動畫製作。

下面是代碼相處一個線上的點:

// Supply T which is an interval along 
// the line where you need an XY point 
// T == 0.00 at the start of the line 
// T == 1.00 at the end of the line 

function getLineXYatT(startPt,endPt,T) { 
    var dx = endPt.x-startPt.x; 
    var dy = endPt.y-startPt.y; 
    var X = startPt.x + dx*T; 
    var Y = startPt.y + dy*T; 
    return({x:X,y:Y}); 
} 

而你需要繪製每條曲線上的每個點,因此您可以在動畫曲線的那些點。

下面是代碼沿貝塞爾曲線得到一分:

// Supply T which is an interval along 
// the curve where you need an XY point 
// T == 0.00 at the start of the line 
// T == 1.00 at the end of the line 

function getCubicBezierXYatT(startPt,controlPt1,controlPt2,endPt,T){ 
    var x=CubicN(T,startPt.x,controlPt1.x,controlPt2.x,endPt.x); 
    var y=CubicN(T,startPt.y,controlPt1.y,controlPt2.y,endPt.y); 
    return({x:x,y:y}); 
} 

// cubic helper formula at T distance 
function CubicN(T, a,b,c,d) { 
    var t2 = T * T; 
    var t3 = t2 * T; 
    return a + (-a * 3 + T * (3 * a - a * T)) * T 
    + (3 * b + T * (-6 * b + b * 3 * T)) * T 
    + (c * 3 - c * 3 * T) * t2 
    + d * t3; 
} 

最後,使用requestAnimationFrame沿線點和曲線點動畫。

這是一個動畫循環的一個例子是逐漸繪製一條線:

http://jsfiddle.net/m1erickson/keLPs/

繪製動畫中的環行:

var lineStart={x:50,y:50}; 
var lineEnd={x:150,y:150}; 
var T=0.00; 
var previousPoint=lineStart; 

animate(); 

function animate() { 

    // if the animation is not done, request another frame 

    if(T<=1.00){ 
     requestAnimationFrame(animate); 
    } 

    // Drawing code goes here 

    var pt=getLineXYatT(lineStart,lineEnd,T); 
    ctx.beginPath(); 
    ctx.moveTo(previousPoint.x,previousPoint.y); 
    ctx.lineTo(pt.x,pt.y); 
    ctx.stroke(); 

    // increment for the next point on the line 

    T+=.01; 
    previousPoint=pt; 
} 

您可以創建一個通用版本上面的函數可以接受一條線的起點/終點,並在該線上進行動畫處理。

創建一個廣義曲線函數,該函數在Bezier曲線上接受4個控制點和動畫。

...你完成了!