How to read pixels of texture?

Hi.

I can’t figure out how to read the pixel data of a texture.

I pass my texture to the script like this:

Main.attributes.add(‘MyTexture’, {
type: ‘asset’,
assetType: ‘texture’
});

And I can read the width, height and format fine, but I can’t figure out how to read the pixels.

The documentation says:

getSource()
Get the pixel data of the texture. If this is a cubemap then an array of 6 images will be returned otherwise a single image.

and

lock(options)
Locks a miplevel of the texture, returning a typed array to be filled with pixel data.

But both methods return: < img src="/api/assets/files/MyTexture.png?id=12274877&t=03d7f77878e2a1a33e3de734d949759d">

Here’s my test project:

https://playcanvas.com/project/552916/overview/get-pixel-data

You are close!

Check this project and the terrain-distribute script on how to read pixel data directly. Most notably these two methods:

TerrainDistribute.prototype.getImageData()
TerrainDistribute.prototype.distribute()

https://playcanvas.com/project/539384/overview/tiled-terrain-manager

https://playcanvas.com/editor/code/539384?tabs=11346077

2 Likes

Thank you for your reply. :slight_smile:

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0 );
var myData = context.getImageData(0, 0, img.width, img.height);

Thank you, I will do that. :slight_smile: