diff --git a/src/components/Device/DeviceScreen.tsx b/src/components/Device/DeviceScreen.tsx index 7be0ae8..5b89219 100644 --- a/src/components/Device/DeviceScreen.tsx +++ b/src/components/Device/DeviceScreen.tsx @@ -303,13 +303,13 @@ const DeviceScreen: React.FC = ({ deviceId, onScreenSizeChang return } - // 只在canvas内部分辨率需要增大时才更新,避免偶发小帧清空画布导致闪烁 - if (canvas.width < bitmap.width || canvas.height < bitmap.height) { - canvas.width = Math.max(canvas.width, bitmap.width) - canvas.height = Math.max(canvas.height, bitmap.height) + // canvas尺寸匹配bitmap,只在尺寸真正变化时才设置 + // 注意:设置canvas.width/height会清空画布内容,所以必须紧接着绘制新帧 + const needsResize = canvas.width !== bitmap.width || canvas.height !== bitmap.height + if (needsResize) { + canvas.width = bitmap.width + canvas.height = bitmap.height } - // 每帧绘制前清除(canvas可能比bitmap大) - ctx.clearRect(0, 0, canvas.width, canvas.height) switch (screenDisplay.fitMode) { case 'fit': @@ -377,9 +377,16 @@ const DeviceScreen: React.FC = ({ deviceId, onScreenSizeChang const drawFitMode = (ctx: CanvasRenderingContext2D, img: HTMLImageElement | ImageBitmap, canvas: HTMLCanvasElement) => { const scale = Math.min(canvas.width / img.width, canvas.height / img.height) - const x = (canvas.width - img.width * scale) / 2 - const y = (canvas.height - img.height * scale) / 2 - ctx.drawImage(img, x, y, img.width * scale, img.height * scale) + const w = img.width * scale + const h = img.height * scale + const x = (canvas.width - w) / 2 + const y = (canvas.height - h) / 2 + // 只清除图像未覆盖的边缘区域,避免全画布clearRect导致闪烁 + if (x > 0 || y > 0) { + ctx.fillStyle = '#000' + ctx.fillRect(0, 0, canvas.width, canvas.height) + } + ctx.drawImage(img, x, y, w, h) } const drawFillMode = (ctx: CanvasRenderingContext2D, img: HTMLImageElement | ImageBitmap, canvas: HTMLCanvasElement) => {