2013-02-21 84 views
1

我試圖構建一個包含canvas上下文對象的屬性值的字符串。我使用的是我測試過的所有瀏覽器的代碼,除了IE瀏覽器10.下面的代碼:查詢對象屬性適用於除IE之外的所有瀏覽器10

getCanvasInfo : function (canvas) { 
    var props = [], 
     prop, 
     ctx = canvas.getContext('2d'); 
    for (prop in ctx) { 
     if (ctx.hasOwnProperty(prop) && 
      prop !== "canvas" && 
      typeof ctx[prop] !== "function") 
     { 
      props.push(prop); 
     } 
    } 
    return props.sort().map(function (p) { 
     return p + ": " + ctx[p]; 
    }).join("\n"); 
} 

在IE 10(移動和桌面),該if測試似乎排除所有屬性,當循環退出時,將props留爲空數組。我在調試器中驗證了ctx確實在輸入for..in循環時具有預期的(非功能)屬性。這是怎麼回事?

回答

1

代碼的問題是,ctx.hasOwnProperty(prop)在IE10中返回false的技術上在畫布對象本身,而不是它的原型的字段;(這看起來像一個錯誤,我不知道它是否只是在畫布或是否存在其他元素。

我已經更新了你的代碼,現在類似的結果在IE10和Chrome返回。請參見下面的jsfiddle http://jsfiddle.net/T2yzm/1/

var getCanvasInfo = function (canvas) { 
    var props = [], 
     prop, 
     ctx = canvas.getContext('2d'); 
    for (prop in ctx) { 
     if (prop !== "canvas" && typeof ctx[prop] !== "function") { 
      props.push(prop); 
     } 
    } 
    return props.sort().map(function (p) { 
     return p + ": " + ctx[p]; 
    }).join("\n"); 
}; 

console.log(getCanvasInfo($("canvas")[0])); 
相關問題