While taking a screenshot of widget in flutter for mobile, is very easy. But if you tried it on web, you got an error. In this story I’m going to show you how you can create a screenshot with library called html2canvas.
All you need is, to get the coordinates of the widget, and the html2canvas will capture it to image like a PNG. Coordinates can fetch like this:
First create an extension to
GlobalKey that can give you coordinates of widget
Now you can add
GlobalKey to your widget, and get its coordinates:
Rect rect = canvasKey.globalPaintBounds;
When you have a coordinates you can call JS with them.
js.context.callMethod('capture', [rect.left, rect.top, rect.right, rect.bottom]);
Now you need to create JS file and added it to your
After that, a png file will download to your device.
You may notice that the file is in poor quality, and you can zoom it as well. Now you can do more trick, increase your widget scale, and than capture it multiple time, and merge results together.
First, add to your widget, a scale to increase resulation, and ClipRect to crop the edges:
double _scale = 1.0;
double _offsetX = 0.0;
double _offsetY = 0.0;ClipRect(
origin: Offset(_offsetX, _offsetY),
After that you can add this method to do the job:
Now you need to add in JS the logic to save the parts, and merge them:
You may want to cover the widget with a loader or something, to hide the process. You can create a div in JS and cover the widget.