Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  122] [ 7]  / answers: 1 / hits: 21875  / 15 Years ago, thu, november 19, 2009, 12:00:00

I have a class with a property that can be an Image (i.e. an IMG element) or a Canvas. When I serialize it to JSON, I need to convert this to a text string. If it is a Canvas, then I can call Canvas#toDataURL. But if it is an Image, I first need to draw it to a Canvas with Canvas#drawImage, then serialize that canvas with toDataURL.



So how do I determine if the object is a Canvas or an Image? (Since Canvas#drawImage is capable of accepting either Image or Canvas objects as an argument, there must be a way.)



I have seen that some programmers test for the existence of certain properties or functions to determine class, but I was wondering if there is a smarter way that won't break if the API presented by these objects changes.


More From » reflection

 Answers
128
function isImage(i) {
return i instanceof HTMLImageElement;
}

[#98279] Sunday, November 15, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronaldo

Total Points: 694
Total Questions: 85
Total Answers: 103

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;