go-rod / rod

A Chrome DevTools Protocol driver for web automation and scraping.
https://go-rod.github.io
MIT License
5k stars 328 forks source link

Screenshot in Emulate error #1034

Open 8763232 opened 2 months ago

8763232 commented 2 months ago
// Screenshot of the area of the element
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,
    }
        //page full Screenshot   Notice :The device resolution is inconsistent with the display resolution
    bin, err := el.page.Context(el.ctx).Screenshot(false, opts)    
    if err != nil {
        return nil, err
    }

    // so that it won't clip the css-transformed element
    shape, err := el.Shape()
    if err != nil {
        return nil, err
    }

    box := shape.Box()   // get el box 

    // TODO: proto.PageCaptureScreenshot has a Clip option, but it's buggy, so now we do in Go.
        // cut the Screenshot ,but this box x/y, Width/Height are inconsistent with the resolution. Will cause screenshot error
       //   window.devicePixelRatio  is not 1,in Emulate that is 3
    return utils.CropImage(bin, quality,  
        int(box.X),
        int(box.Y),
        int(box.Width),
        int(box.Height),
    )
}

Rod Version: v0.114.6

Need to recalculate coordinates to take screenshot correctly

github-actions[bot] commented 2 months ago

Please fix the format of your markdown:

37 MD031/blanks-around-fences Fenced code blocks should be surrounded by blank lines [Context: "```"]

generated by check-issue

8763232 commented 2 months ago
        res, err := el.Eval(`() => window.devicePixelRatio`)
    if err != nil {
        return nil, err
    }
    devicePixelRatio, _ := strconv.Atoi(res.Value.Str())

    box := shape.Box()
    // TODO: proto.PageCaptureScreenshot has a Clip option, but it's buggy, so now we do in Go.
    return CropImage(bin, quality,
        int(box.X)*devicePixelRatio,
        int(box.Y)*devicePixelRatio,
        int(box.Width)*devicePixelRatio,
        int(box.Height)*devicePixelRatio,
    )
ysmood commented 2 months ago

Could you create a test case to reproduce it?