( div: HTMLDivElement, paddingV: number = 0, paddingH: number = 0 )
| 92 | } |
| 93 | |
| 94 | export async function captureDivToClipboard( |
| 95 | div: HTMLDivElement, |
| 96 | paddingV: number = 0, |
| 97 | paddingH: number = 0 |
| 98 | ): Promise<boolean> { |
| 99 | try { |
| 100 | // Check if the input is a valid div element |
| 101 | if (!(div instanceof HTMLDivElement)) { |
| 102 | throw new Error('Invalid input: The provided element is not a valid HTMLDivElement.') |
| 103 | } |
| 104 | |
| 105 | // Get the original size and position of the div |
| 106 | const rect = div.getBoundingClientRect() |
| 107 | const width = rect.width + paddingH * 2 // Add horizontal padding |
| 108 | const height = rect.height + paddingV * 2 // Add vertical padding |
| 109 | |
| 110 | // Create a temporary container to render the content with padding |
| 111 | const tempDiv = document.createElement('div') |
| 112 | tempDiv.style.position = 'absolute' |
| 113 | tempDiv.style.top = '-9999px' // Move out of the visible area |
| 114 | tempDiv.style.width = `${width}px` |
| 115 | tempDiv.style.height = `${height}px` |
| 116 | tempDiv.style.boxSizing = 'border-box' |
| 117 | tempDiv.style.background = 'white' // Set background color to avoid transparency |
| 118 | |
| 119 | const node = div.cloneNode(true) as HTMLDivElement |
| 120 | node.style.padding = `${paddingV}px ${paddingH}px` |
| 121 | tempDiv.appendChild(node) |
| 122 | document.body.appendChild(tempDiv) |
| 123 | |
| 124 | // Use html2canvas to convert the temporary container to a canvas |
| 125 | const canvas = await html2canvas(tempDiv, { |
| 126 | scale: window.devicePixelRatio, // Ensure clarity on high-resolution devices |
| 127 | useCORS: true // Enable this option if the div contains cross-origin images |
| 128 | }) |
| 129 | |
| 130 | // Remove the temporary container |
| 131 | document.body.removeChild(tempDiv) |
| 132 | |
| 133 | // Convert the canvas to a Blob object |
| 134 | const blob = await new Promise<Blob>((resolve, reject) => { |
| 135 | canvas.toBlob((blob) => { |
| 136 | if (blob) { |
| 137 | resolve(blob) |
| 138 | } else { |
| 139 | reject(new Error('Failed to convert canvas to Blob.')) |
| 140 | } |
| 141 | }, 'image/png') |
| 142 | }) |
| 143 | |
| 144 | // Use the Clipboard API to write the Blob to the clipboard |
| 145 | await navigator.clipboard.write([ |
| 146 | new ClipboardItem({ |
| 147 | [blob.type]: blob |
| 148 | }) |
| 149 | ]) |
| 150 | |
| 151 | console.log('Image with padding successfully copied to clipboard!') |
nothing calls this directly
no outgoing calls
no test coverage detected