Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 413
Paul Chernoch Avatar asked Nov 19 '09 02:11

Paul Chernoch


People also ask

How do you check if an element is an image Javascript?

Check if element is an Image <img /> using jQueryfind() method to check if the element in an image or with <img /> tag. Using the . attr() method I can get the src and id of each image. Change the value img to p and you will get the details about the paragraph (properties and text) inside the container.

How can you tell if something is drawn on canvas?

I found out that when the canvas is empty all of the pixel data returns 0 in all index positions of the array. So I used that to detect if there is any 0 's or not and as the result I made it so it returns a boolean. If the canvas has been drawn on then it returns true and if it hasn't then it returns false .

What is image canvas?

The Canvas Size command is used for adding space around a photo or essentially cropping the image by reducing the available space. More Detail: For example, let's assume you have an image that is currently sized at 8-inches by 12-inches at 300 pixels per inch (2,400 by 3,600 pixels).


2 Answers

function isImage(i) {
    return i instanceof HTMLImageElement;
}
like image 95
James Avatar answered Oct 12 '22 12:10

James


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

var isImg = (element.nodeName.toLowerCase() === 'img');
like image 21
Crescent Fresh Avatar answered Oct 12 '22 12:10

Crescent Fresh