diff --git a/src/misc/image-data.js b/src/misc/image-data.js index 32803f27..b31a4af7 100644 --- a/src/misc/image-data.js +++ b/src/misc/image-data.js @@ -4,26 +4,31 @@ import { hasFired } from './promisify.js' const canvas = document.createElement('canvas') const canvasCtx = canvas.getContext('2d') -export function imageDataFromImage (imageElement) { - canvas.width = imageElement.naturalWidth - canvas.height = imageElement.naturalHeight +canvas.width = 1920 +canvas.height = 1080 - const bounds = [0, 0, canvas.width, canvas.height] +function imageDataFromCanvas (canvasImageSource, width, height) { + const scalingRatio = Math.min(1, canvas.width / width, canvas.height / height) + const widthScaled = scalingRatio * width + const heightScaled = scalingRatio * height - canvasCtx.drawImage(imageElement, ...bounds) + canvasCtx.drawImage(canvasImageSource, 0, 0, widthScaled, heightScaled) - return canvasCtx.getImageData(...bounds) + return canvasCtx.getImageData(0, 0, widthScaled, heightScaled) } -export function imageDataFromVideo (videoElement) { - canvas.width = videoElement.videoWidth - canvas.height = videoElement.videoHeight +export function imageDataFromImage (imageElement) { + const width = imageElement.naturalWidth + const height = imageElement.naturalHeight - const bounds = [0, 0, canvas.width, canvas.height] + return imageDataFromCanvas(imageElement, width, height) +} - canvasCtx.drawImage(videoElement, ...bounds) +export function imageDataFromVideo (videoElement) { + const width = videoElement.videoWidth + const height = videoElement.videoHeight - return canvasCtx.getImageData(...bounds) + return imageDataFromCanvas(videoElement, width, height) } export async function imageDataFromUrl (url) {