Skip to content

Commit

Permalink
Merge pull request #65 from martinRenou/apply_synced_image
Browse files Browse the repository at this point in the history
Draw synced data at canvas creation
  • Loading branch information
martinRenou authored Jan 17, 2020
2 parents dfb9791 + e6f80a2 commit 2cf1c77
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
15 changes: 15 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,18 @@ async function toBytes(canvas: HTMLCanvasElement) : Promise<Uint8ClampedArray> {
reader.readAsArrayBuffer(blob);
});
}

export
async function fromBytes(array: Uint8ClampedArray) : Promise<HTMLImageElement> {
const blob = new Blob([array]);

return new Promise<HTMLImageElement>((resolve, reject) => {
const img = new Image();

img.onload = () => {
resolve(img);
}

img.src = URL.createObjectURL(blob);
});
}
34 changes: 29 additions & 5 deletions src/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from './version';

import {
getArg, toBytes
getArg, toBytes, fromBytes
} from './utils';


Expand All @@ -22,6 +22,18 @@ function getContext(canvas: HTMLCanvasElement) {
return context;
}

function serializeImageData(array: Uint8ClampedArray) {
return new DataView(array.buffer.slice(0));
}

function deserializeImageData(dataview: DataView | null) {
if (dataview === null) {
return null;
}

return new Uint8ClampedArray(dataview.buffer);
}


export
class CanvasModel extends DOMWidgetModel {
Expand All @@ -41,9 +53,10 @@ class CanvasModel extends DOMWidgetModel {

static serializers: ISerializers = {
...DOMWidgetModel.serializers,
image_data: { serialize: (bytes: Uint8ClampedArray) => {
return new DataView(bytes.buffer.slice(0));
}}
image_data: {
serialize: serializeImageData,
deserialize: deserializeImageData
}
}

initialize(attributes: any, options: any) {
Expand All @@ -53,13 +66,24 @@ class CanvasModel extends DOMWidgetModel {
this.ctx = getContext(this.canvas);

this.resizeCanvas();
this.drawImageData();

this.on('change:size', this.resizeCanvas.bind(this));
this.on('msg:custom', this.onCommand.bind(this));

this.send({ event: 'client_ready' }, {});
}

private async drawImageData() {
if (this.get('sync_image_data') && this.get('image_data') !== null) {
const img = await fromBytes(this.get('image_data'));

this.ctx.drawImage(img, 0, 0);

this.trigger('new-frame');
}
}

private async onCommand(command: any, buffers: any) {
await this.processCommand(command, buffers);

Expand Down Expand Up @@ -328,7 +352,7 @@ class CanvasView extends DOMWidgetView {
}

updateCanvas() {
this.clear();
this.clear();
this.ctx.drawImage(this.model.canvas, 0, 0);
}

Expand Down

0 comments on commit 2cf1c77

Please sign in to comment.