Skip to content

Commit bb59e4e

Browse files
committed
Pass image data from JavaScript to C++/WASM
1 parent 1a0f498 commit bb59e4e

File tree

3 files changed

+32
-8
lines changed

3 files changed

+32
-8
lines changed

CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,4 @@ file(GLOB opencv_js "${OPENCV_DIR}/build_wasm/lib/*.a")
3232
target_link_libraries(hello ${opencv_js})
3333

3434
# Specify linker arguments
35-
set_target_properties(hello PROPERTIES LINK_FLAGS "-s ENVIRONMENT=web -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','UTF8ToString']")
35+
set_target_properties(hello PROPERTIES LINK_FLAGS "-s ENVIRONMENT=web -s EXTRA_EXPORTED_RUNTIME_METHODS=['cwrap']")

src/hello.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@ extern "C" {
88
#endif
99

1010
EMSCRIPTEN_KEEPALIVE
11-
void fred(int n, const char *s) {
11+
void processImage(uchar *array, int width, int height) {
12+
cv::Mat mat(height, width, CV_8UC4, array);
1213
EM_ASM_({
13-
console.log(`[fred] n: ${$0}; s: ${Module.UTF8ToString($1)}`)
14-
}, n, s);
14+
console.log(`[processImage] width: ${$0}; height: ${$1}; array[0]: ${$2}; array[1]: ${$3}; array[2]: ${$4}`)
15+
}, width, height, array[0], array[1], array[2]);
1516
}
1617

1718
#ifdef __cplusplus

src/index.js

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,35 @@ window.Module = {
55
}
66
}
77

8-
const onProcessImage = () => {
8+
const processImageBtn = document.getElementById('process-image-btn')
9+
const img = document.getElementById('input-image')
10+
11+
const getImageData = () => {
12+
const canvas = document.createElement('canvas')
13+
canvas.width = img.width
14+
canvas.height = img.height
15+
ctx = canvas.getContext('2d')
16+
ctx.drawImage(img, 0, 0, img.width, img.height)
17+
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
18+
return imageData
19+
}
20+
21+
const onProcessImage = processImage => () => {
922
console.log('[onProcessImage]')
10-
Module.ccall('fred', null, ['number', 'string'], [42, 'Hello'])
23+
const { data, width, height } = getImageData()
24+
processImage(data, width, height)
25+
}
26+
27+
const wrapProcessImage = module => {
28+
const ident = 'processImage'
29+
const returnType = null
30+
const argTypes = ['array', 'number', 'number']
31+
const processImage = module.cwrap(ident, returnType, argTypes)
32+
return processImage
1133
}
1234

13-
const init = Module => {
35+
const init = module => {
1436
console.log('[init]')
15-
document.getElementById('process-image-btn').addEventListener('click', onProcessImage)
37+
const processImage = wrapProcessImage(module)
38+
processImageBtn.addEventListener('click', onProcessImage(processImage))
1639
}

0 commit comments

Comments
 (0)