2017-08-06 112 views
0

我想學習如何使用純香草JavaScript爲SVG創建動畫效果。我想讓圓圈成長和縮小,同時在每個圓圈的頂部顯示一個標籤,用一個代表其當前尺寸的值。使用純Javascript動畫SVG

索爾到目前爲止,我有以下SVG:

<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg"> 
     <path fill="none" d="M-1-1h502v302H-1z"/> 
     <g> 
      <path stroke-linecap="null" stroke-linejoin="null" stroke-opacity="null" stroke-width="4.5" stroke="#000" fill="none" d="M39.5 31.5v239M463.5 269.5l-422-1"/> 
      <ellipse stroke="#bf0000" ry="65.5" rx="67" cy="165" cx="158.5" stroke-width="4.5" fill="none"/> 
      <ellipse stroke="#007f00" ry="65.5" rx="67" cy="165" cx="361.5" stroke-width="4.5" fill="none"/> 
     </g> 
     </svg> 

下面的JS代碼:

console.log("DOM Ready!"); 

var redCircle = document.getElementsByClassName('red'); 

var current = 0; 
var destination = 700; 
var friction = 0.04; 


function loop() { 
    console.log(redCircle.style.width); 
    current += (destination - current) * friction; 
    redCircle.style.width = (current * 0.5 + 'px'); 
    if (current >= destination - 0.1) { 
    clearInterval(animation); 
    } 
} 
var animation = setInterval(loop, 20); 

我的問題是,開發者工具的console.log說:

Uncaught TypeError: Cannot set property 'width' of undefined at loop 

回答

1

document.getElementsByClassName返回一個不是對象的數組。你的html中也沒有名爲'red'的類,所以你的腳本返回的數組是= []。一個空陣列。當你調用.style時,你基本上調用[] .style。由於樣式不作爲數組的屬性存在(它是未定義的)。然後嘗試獲取不存在的屬性(.width)([]。style),這是不可能的,所以JavaScript除了拋出一個錯誤外什麼都不做。

console.log("DOM Ready!"); 
 

 
var redCircle = document.getElementsByClassName('red'); 
 

 
var current = 0; 
 
var destination = 700; 
 
var friction = 0.04; 
 

 
function loop() { 
 
    // console.log(redCircle[0].style); 
 
    current += (destination - current) * friction; 
 
    redCircle[0].style.width = (current * 0.5 + 'px'); 
 
    if (current >= destination - 0.1) { 
 
    clearInterval(animation); 
 
    } 
 
} 
 
var animation = setInterval(loop, 20);
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg" class="red"> 
 
     <path fill="none" d="M-1-1h502v302H-1z"/> 
 
     <g> 
 
      <path stroke-linecap="null" stroke-linejoin="null" stroke-opacity="null" stroke-width="4.5" stroke="#000" fill="none" d="M39.5 31.5v239M463.5 269.5l-422-1"/> 
 
      <ellipse stroke="#bf0000" ry="65.5" rx="67" cy="165" cx="158.5" stroke-width="4.5" fill="none"/> 
 
      <ellipse stroke="#007f00" ry="65.5" rx="67" cy="165" cx="361.5" stroke-width="4.5" fill="none"/> 
 
     </g> 
 
     </svg>