61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/chromedp/cdproto/emulation"
|
|
"github.com/chromedp/cdproto/page"
|
|
"github.com/chromedp/chromedp"
|
|
)
|
|
|
|
// elementScreenshot takes a screenshot of a specific element.
|
|
func elementScreenshot(urlstr, sel string, res *[]byte) chromedp.Tasks {
|
|
return chromedp.Tasks{
|
|
chromedp.Navigate(urlstr),
|
|
chromedp.WaitVisible(sel, chromedp.ByID),
|
|
chromedp.Screenshot(sel, res, chromedp.NodeVisible, chromedp.ByID),
|
|
}
|
|
}
|
|
|
|
// fullScreenshot takes a screenshot of the entire browser viewport.
|
|
func fullScreenshot(urlstr string, resolution [2]int64, quality int64, delay time.Duration, res *[]byte) chromedp.Tasks {
|
|
return chromedp.Tasks{
|
|
chromedp.Navigate(urlstr),
|
|
chromedp.Sleep(delay),
|
|
chromedp.ActionFunc(func(ctx context.Context) error {
|
|
// get layout metrics
|
|
_, _, _, _, _, cssContentSize, err := page.GetLayoutMetrics().Do(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// force viewport emulation
|
|
err = emulation.SetDeviceMetricsOverride(resolution[0], resolution[1], 1, false).
|
|
WithScreenOrientation(&emulation.ScreenOrientation{
|
|
Type: emulation.OrientationTypePortraitPrimary,
|
|
Angle: 0,
|
|
}).
|
|
Do(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// capture screenshot
|
|
*res, err = page.CaptureScreenshot().
|
|
WithQuality(quality).
|
|
WithClip(&page.Viewport{
|
|
X: cssContentSize.X,
|
|
Y: cssContentSize.Y,
|
|
Width: float64(resolution[0]),
|
|
Height: float64(resolution[1]),
|
|
Scale: 1,
|
|
}).Do(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}),
|
|
}
|
|
}
|