@@ -10,7 +10,7 @@ import {
1010} from './version' ;
1111
1212import {
13- getArg , toBytes
13+ getArg , toBytes , fromBytes
1414} from './utils' ;
1515
1616
@@ -22,6 +22,18 @@ function getContext(canvas: HTMLCanvasElement) {
2222 return context ;
2323}
2424
25+ function serializeImageData ( array : Uint8ClampedArray ) {
26+ return new DataView ( array . buffer . slice ( 0 ) ) ;
27+ }
28+
29+ function deserializeImageData ( dataview : DataView | null ) {
30+ if ( dataview === null ) {
31+ return null ;
32+ }
33+
34+ return new Uint8ClampedArray ( dataview . buffer ) ;
35+ }
36+
2537
2638export
2739class CanvasModel extends DOMWidgetModel {
@@ -41,9 +53,10 @@ class CanvasModel extends DOMWidgetModel {
4153
4254 static serializers : ISerializers = {
4355 ...DOMWidgetModel . serializers ,
44- image_data : { serialize : ( bytes : Uint8ClampedArray ) => {
45- return new DataView ( bytes . buffer . slice ( 0 ) ) ;
46- } }
56+ image_data : {
57+ serialize : serializeImageData ,
58+ deserialize : deserializeImageData
59+ }
4760 }
4861
4962 initialize ( attributes : any , options : any ) {
@@ -53,13 +66,24 @@ class CanvasModel extends DOMWidgetModel {
5366 this . ctx = getContext ( this . canvas ) ;
5467
5568 this . resizeCanvas ( ) ;
69+ this . drawImageData ( ) ;
5670
5771 this . on ( 'change:size' , this . resizeCanvas . bind ( this ) ) ;
5872 this . on ( 'msg:custom' , this . onCommand . bind ( this ) ) ;
5973
6074 this . send ( { event : 'client_ready' } , { } ) ;
6175 }
6276
77+ private async drawImageData ( ) {
78+ if ( this . get ( 'sync_image_data' ) && this . get ( 'image_data' ) !== null ) {
79+ const img = await fromBytes ( this . get ( 'image_data' ) ) ;
80+
81+ this . ctx . drawImage ( img , 0 , 0 ) ;
82+
83+ this . trigger ( 'new-frame' ) ;
84+ }
85+ }
86+
6387 private async onCommand ( command : any , buffers : any ) {
6488 await this . processCommand ( command , buffers ) ;
6589
@@ -328,7 +352,7 @@ class CanvasView extends DOMWidgetView {
328352 }
329353
330354 updateCanvas ( ) {
331- this . clear ( ) ;
355+ this . clear ( ) ;
332356 this . ctx . drawImage ( this . model . canvas , 0 , 0 ) ;
333357 }
334358
0 commit comments