开发者

How can I tell if a javascript object is an Image or a Canvas?

开发者 https://www.devze.com 2022-12-11 16:56 出处:网络
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#t

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 开发者_Go百科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.


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


If cross-window/frame compatibility is a concern you can check nodeName:

var isImg = (element.nodeName.toLowerCase() === 'img');


function isCanvas(i) {
    return i instanceof HTMLCanvasElement;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号