@@ -486,11 +486,56 @@ describe("PDF viewer", () => {
486486 const pageOne = document . querySelector (
487487 `.page[data-page-number='${ pageNumber } ']`
488488 ) ;
489+ function getContextFromCanvas ( canvas ) {
490+ try {
491+ return canvas . getContext ( "2d" , { willReadFrequently : true } ) ;
492+ } catch {
493+ // Can happen when the canvas has been transferred to OffscreenCanvas.
494+ }
495+
496+ let tempCanvas ;
497+ if ( typeof OffscreenCanvas === "function" ) {
498+ tempCanvas = new OffscreenCanvas ( canvas . width , canvas . height ) ;
499+ } else {
500+ tempCanvas = document . createElement ( "canvas" ) ;
501+ tempCanvas . width = canvas . width ;
502+ tempCanvas . height = canvas . height ;
503+ }
504+ const tempCtx = tempCanvas . getContext ( "2d" , {
505+ willReadFrequently : true ,
506+ } ) ;
507+ tempCtx . drawImage ( canvas , 0 , 0 ) ;
508+ return tempCtx ;
509+ }
510+
511+ if ( ! pageOne ) {
512+ return [ ] ;
513+ }
514+
489515 return Array . from ( pageOne . querySelectorAll ( "canvas" ) , canvas => {
490516 const { width, height } = canvas ;
491- const ctx = canvas . getContext ( "2d" ) ;
492- const topLeft = ctx . getImageData ( 2 , 2 , 1 , 1 ) . data ;
493- const bottomRight = ctx . getImageData ( width - 3 , height - 3 , 1 , 1 ) . data ;
517+ if ( width === 0 || height === 0 ) {
518+ return {
519+ size : 0 ,
520+ width,
521+ height,
522+ topLeft : null ,
523+ bottomRight : null ,
524+ } ;
525+ }
526+ const ctx = getContextFromCanvas ( canvas ) ;
527+ const topLeft = ctx . getImageData (
528+ Math . min ( 2 , width - 1 ) ,
529+ Math . min ( 2 , height - 1 ) ,
530+ 1 ,
531+ 1
532+ ) . data ;
533+ const bottomRight = ctx . getImageData (
534+ Math . max ( 0 , width - 3 ) ,
535+ Math . max ( 0 , height - 3 ) ,
536+ 1 ,
537+ 1
538+ ) . data ;
494539 return {
495540 size : width * height ,
496541 width,
0 commit comments