# BitmapLayer
import {BitmapLayerDemo} from '@site/src/doc-demos/layers';
The `BitmapLayer` renders a bitmap at specified boundaries.
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
```js
import {Deck} from '@deck.gl/core';
import {BitmapLayer} from '@deck.gl/layers';
const layer = new BitmapLayer({
id: 'BitmapLayer',
bounds: [-122.519, 37.7045, -122.355, 37.829],
image: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-districts.png',
pickable: true
});
new Deck({
initialViewState: {
longitude: -122.4,
latitude: 37.74,
zoom: 11
},
controller: true,
getTooltip: ({bitmap}) => bitmap && `${bitmap.pixel}`,
layers: [layer]
});
```
```ts
import {Deck} from '@deck.gl/core';
import {BitmapLayer, BitmapLayerPickingInfo} from '@deck.gl/layers';
const layer = new BitmapLayer({
id: 'BitmapLayer',
bounds: [-122.519, 37.7045, -122.355, 37.829],
image: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-districts.png',
pickable: true
});
new Deck({
initialViewState: {
longitude: -122.4,
latitude: 37.74,
zoom: 11
},
controller: true,
getTooltip: ({bitmap}: BitmapLayerPickingInfo) => bitmap && `${bitmap.pixel}`,
layers: [layer]
});
```
```tsx
import React from 'react';
import {DeckGL} from '@deck.gl/react';
import {BitmapLayer} from '@deck.gl/layers';
import type {BitmapLayerPickingInfo} from '@deck.gl/layers';
function App() {
const layer = new BitmapLayer({
id: 'BitmapLayer',
bounds: [-122.519, 37.7045, -122.355, 37.829],
image: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-districts.png',
pickable: true
});
return bitmap && `${bitmap.pixel}`}
layers={[layer]}
/>;
}
```
## Installation
To install the dependencies from NPM:
```bash
npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers
```
```ts
import {BitmapLayer} from '@deck.gl/layers';
import type {BitmapLayerProps, BitmapLayerPickingInfo} from '@deck.gl/layers';
new BitmapLayer(...props: BitmapLayerProps);
```
To use pre-bundled scripts:
```html
```
```js
new deck.BitmapLayer({});
```
### Render an image on a triangle mesh
Pair [`positions`](#positions) with [`texCoords`](#texcoords) to map an image onto a custom mesh.
```ts
import {BitmapLayer} from '@deck.gl/layers';
import {Field, FixedSizeList, Float32, vectorFromArray} from 'apache-arrow';
const xy = new FixedSizeList(2, new Field('value', new Float32(), false));
const layer = new BitmapLayer({
id: 'image-triangle',
image: '/image.png',
positions: vectorFromArray([[-122, 37], [-121, 37], [-122, 38]], xy),
texCoords: vectorFromArray([[0, 1], [1, 1], [0, 0]], xy)
});
```
## Properties
### Data
#### `image` (string | Texture | Image | ImageData | HTMLCanvasElement | HTMLVideoElement | ImageBitmap | Promise | object) {#image}
- Default `null`.
The image to display.
- If a string is supplied, it is interpreted as a URL or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs).
- One of the following, or a Promise that resolves to one of the following:
+ One of the valid [pixel sources for WebGL2 texture](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D)
+ A luma.gl [Texture](https://luma.gl/docs/api-reference/core/resources/texture) instance
+ A plain object that can be passed to the `Texture` constructor, e.g. `{width: , height: , data: }`. Note that whenever this object shallowly changes, a new texture will be created.
The image data will be converted to a [Texture](https://luma.gl/docs/api-reference/core/resources/texture) object. See `textureParameters` prop for advanced customization.
#### `bounds` (number[4] | Position[4]) {#bounds}
When supplied, `positions` replaces the quad from `bounds`. With GPU-only positions,
`bounds` still sets the footprint for view fitting.
Supported formats:
- Coordinates of the bounding box of the bitmap `[left, bottom, right, top]`
- Coordinates of four corners of the bitmap, should follow the sequence of `[[left, bottom], [left, top], [right, top], [right, bottom]]`. Each position could optionally contain a third component `z`.
`left` and `right` refers to the world longitude/x at the corresponding side of the image.
`top` and `bottom` refers to the world latitude/y at the corresponding side of the image.
#### `positions` (object, optional) {#positions}
* Default: `null`
Mesh vertex positions, replacing the quad from `bounds`. Accepts numeric Arrow XY/XYZ
fixed-size lists or a `float32x2`/`float32x3` GPUVector. With GPU-only positions,
set `bounds` to the footprint for view fitting.
#### `texCoords` (object, optional) {#texcoords}
* Default: `null`
Texture coordinates per vertex as Arrow XY fixed-size lists or a `float32x2` GPUVector.
Supply with `positions` and the same vertex count. `(0, 0)` is the image's top-left corner.
These coordinates take precedence over `_imageCoordinateSystem`.
#### `indices` (object, optional) {#indices}
* Default: `null`
Optional `uint16` or `uint32` triangle indices. Without indices, every three vertices form
a triangle. Removing all mesh props restores the quad from `bounds`.
Remarks for `positions`, `texCoords` and `indices`:
* Each input must be a single Arrow chunk or GPU buffer.
* GPUVector inputs remain owned by the application. Keep them alive while the layer uses them.
* GPU-only positions require a view that does not convert positions on the CPU.
* Mesh inputs cannot be async iterables, and mesh changes do not transition.
* Mesh inputs cannot be combined with a positive `_projectionTolerance`.
* Pass a new Arrow vector to update the mesh. See [Using with Arrow](../../developer-guide/using-with-arrow.md#loading-and-updates).
#### `imageMapping` (object, optional) {#imagemapping}
* Default: `null`
Use `imageMapping` when the image and mesh use different projections, such as a Web Mercator
image draped on a longitude/latitude mesh. The layer computes `texCoords` for each vertex.
- `bounds` is the image rectangle `[left, bottom, right, top]` in `imageCRS` units.
- `imageCRS` describes the image rectangle, for example a PROJ string for Web Mercator.
- `positionCRS` describes the raw mesh positions. Omit it to use the layer's absolute
[`coordinateSystem`](../core/layer.md#coordinatesystem) when it has no model matrix or coordinate
offset. Keep an explicit `positionCRS` consistent with the rendered positions.
- `maxEdgeLength` optionally splits edges longer than this positive length in source position
units. Edge length includes Z. Omit it to keep the supplied triangles.
Without `positions`, the layer builds the mesh from its [`bounds`](#bounds), using the view's
subdivision step. Coordinates outside the image rectangle sample according to
[`textureParameters`](#textureparameters).
```ts
new BitmapLayer({
image,
positions, // Arrow longitude/latitude positions in degrees
coordinateSystem: 'lnglat',
imageMapping: {
bounds: [left, bottom, right, top], // Web Mercator meters
imageCRS: '+proj=merc +a=6378137 +b=6378137 +units=m'
}
});
```
Remarks:
* `imageMapping` replaces `texCoords` and the experimental `_imageCoordinateSystem` for this mesh.
The experimental setting remains available for bounds-only rendering without a mapping.
* Positions must be CPU-readable Arrow columns. GPU-only meshes require explicit `texCoords`.
* Split projection seams and clip to the image CRS's valid area before supplying the mesh.
* Cannot be combined with a positive `_projectionTolerance`.
* Very small `maxEdgeLength` values can exceed refinement limits and raise an error.
#### `_projectionTolerance` (number, optional) {#_projectiontolerance}
* Default: `0`
> Note: This prop is experimental
Maximum sampled projection error in meters when a preprojecting view bends the image. Zero retains the `resolution` grid. Requires CPU preprojection and does not support `coordinateSystem: 'cartesian'`. See [Adaptive refinement](../core/custom-projection-view.md#adaptive-refinement).
#### `loadOptions` (object, optional) {#loadoptions}
On top of the [default options](../core/layer.md#loadoptions), also accepts options for the following loaders:
- [ImageLoader](https://loaders.gl/modules/images/docs/api-reference/image-loader) if the `image` prop is an URL
#### `textureParameters` (object) {#textureparameters}
Customize the [texture parameters](https://luma.gl/docs/api-reference/core/resources/sampler#samplerprops).
If not specified, the layer uses the following defaults to create a linearly smoothed texture from `image`:
```ts
{
minFilter: 'linear',
magFilter: 'linear',
mipmapFilter: 'linear',
addressModeU: 'clamp-to-edge',
addressModeV: 'clamp-to-edge'
}
```
For example, to remove smoothing and achieve a pixelated appearance:
```ts
new BitmapLayer({
// ...
textureParameters: {
minFilter: 'nearest',
magFilter: 'nearest'
}
})
```
This prop is only used when `image` initially loads or changes.
#### `_imageCoordinateSystem` (string, optional) {#_imagecoordinatesystem}
> Note: this prop is experimental.
Specifies how image coordinates should be geographically interpreted.
By default, the image is uniformly stretched to fill the geometry defined by `bounds`. This might not be desirable if the image is encoded in a different coordinate system from the projection that the layer is using. For example, a [satellite image encoded in longitude/latitude](https://en.wikipedia.org/wiki/File:Whole_world_-_land_and_oceans_12000.jpg) should not be interpreted linearly when placed in a Web Mercator visualization.
This prop allows you to explicitly inform the layer of the coordinate system of the image:
- `'default'` to use the layer's default image interpretation
- `'lnglat'` if x-axis maps to longitude and y-axis maps to latitude
- `'cartesian'` if the image is pre-projected into the Web Mercator plane.
This option only works with geospatial views and `bounds` that is orthogonal (`[left, bottom, right, top]`).
See the article on [Coordinate Systems](../../developer-guide/coordinate-systems.md) for more information.
### Render Options
#### `desaturate` (number)  {#desaturate}
- Default `0`
The desaturation of the bitmap. Between `[0, 1]`. `0` being the original color and `1` being grayscale.
#### `transparentColor` (Color)  {#transparentcolor}
- Default `[0, 0, 0, 0]`
The color to use for transparent pixels, in `[r, g, b, a]`. Each component is in the `[0, 255]` range. Equivalent to overlaying the image over a background in this color.
#### `tintColor` (Color)  {#tintcolor}
- Default `[255, 255, 255]`
The color to tint the bitmap by, in `[r, g, b]`. Each component is in the `[0, 255]` range.
With Deck's [`normalizedColors`](../core/deck.md#normalizedcolors), plain arrays for `transparentColor` and `tintColor` on a top-level layer use 0–1 channels. Built-in defaults and byte typed arrays retain their byte encoding.
## Pixel Picking
The [picking info](../../developer-guide/interactivity.md#the-pickinginfo-object) passed to callbacks (`onHover`, `onClick`, etc.) provides information on which pixel was picked. It contains an additional `bitmap` field if applicable:
- `bitmap`
+ `pixel` (`[x: number, y: number]`) Integer coordinates into the bitmap
+ `size` (`{width: number; height: number}`) Size of bitmap in pixels
+ `uv` (`[u: number, v: number]`) Normalized (0-1) floating point coordinates
Note that the `bitmap` field can be `null` if on mouse leave or if the bitmap has not yet loaded.
The following code reads the picked pixel color from the bitmap when the layer is clicked:
```ts
new BitmapLayer({
image: './my-image.png',
bounds: [-122.45, 37.75, -122.43, 37.78],
pickable: true,
onClick: ({bitmap, layer}) => {
if (bitmap) {
const {device} = layer.context;
const pixelColor = device.readPixelsToArrayWebGL(layer.props.image, {
sourceX: bitmap.pixel[0],
sourceY: bitmap.pixel[1],
sourceWidth: 1,
sourceHeight: 1
});
console.log('Color at picked pixel:', pixelColor);
}
}
})
```
## Source
[modules/layers/src/bitmap-layer](https://github.com/visgl/deck.gl/tree/master/modules/layers/src/bitmap-layer)