Reputation: 59
I'm using javascript to program a simple web game, it works by drawing the png map on a html canvas where the colors on the map are coded as a game object (black is a wall, red is a spike).
I wanted to detect the color of the pixel the player goes to, but the problem is that every computer processes the png image in a slightly different way based on its settings (at least that's what I understood).
Can I, instead of checking the color drawn on the canvas, get the color of the pixel of the actual png image (so that's the same on every machine)? Do I have to use raw pixel data? If yes, how does that work?
Also, should this help me? (I tried to understand that but I couldn't)
I'm not sure that's possible to do with javascript, but maybe with php or something else.
Thank you for your time
Upvotes: 3
Views: 1901
Reputation: 639
If you're making a game, I wonder why you're trying to detect the color. Are you going to use your image as a map editor? Most image files are slow, heavy, and have to go through decoding. I think you're going to use the image file as a map because it's convenient to create, but I think it's more efficient to using the vector object for use in games. For example, SVG files are easy to make and you can use them separately in the way you think. Instead of using a file with a known extension, you can create your own object and object editor separately.
Anyway, as I left a comment, I found the library you need. It is a library that can decode PNG files on the browser, which reads the binary of the PNG file and returns the byte analysis result to the object. You can check pixel information in the data field and decoding takes a considerable amount of time.
import UPNG from "upng-js";
const input = document.getElementById("upload") as HTMLInputElement;
input.onchange = async (ev) => {
const file = input.files?.[0];
if (!file) return;
if (file.type !== "image/png") return;
const result = UPNG.decode(await file.arrayBuffer());
console.log(result);
};
You can find these libraries, view the PNG binary structure and implement them yourself, but I don't recommend them because I think it will be a very tiring task. Anyway, it is also possible to read and write files through Blob
and Arraybuffer
in the browser.
Upvotes: 2