#1034·rod

在 Emulate 中截图出错

作者: 8763232创建于 2024年4月2日更新于 2026年9月8日
标签enhance
go
// 截取元素区域的屏幕截图
func (el *Element) Screenshot(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error) {
	err := el.ScrollIntoView()
	if err != nil {
		return nil, err
	}

	opts := &proto.PageCaptureScreenshot{
		Quality: gson.Int(quality),
		Format:  format,
	}
        // 完整屏幕截图  注意:设备分辨率与显示分辨率不一致
	bin, err := el.page.Context(el.ctx).Screenshot(false, opts)    
	if err != nil {
		return nil, err
	}

	// 避免裁剪css变换的元素
	shape, err := el.Shape()
	if err != nil {
		return nil, err
	}

	box := shape.Box()  // 获取 el 盒子
	// TODO: proto.PageCaptureScreenshot 具有 Clip 选项,但它存在 bug,因此现在我们在 Go 中执行裁剪。
        // 截取屏幕截图,但此盒子的 x/y、宽度/高度与分辨率不一致。这将导致屏幕截图错误
       // window.devicePixelRatio 不是 1,在模拟中为 3
	return utils.CropImage(bin, quality, 
		int(box.X),
		int(box.Y),
		int(box.Width),
		int(box.Height),
	)
}
Rod 版本: v0.114.6