screenshot.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { toJpeg as ElToJpg, toPng as ElToPng } from "html-to-image";
  2. import { ref } from "vue";
  3. import type { Options as HTMLToImageOptions } from "html-to-image/es/types";
  4. import type { ImageType, UseScreenshot, UseScreenshotOptions } from "./types";
  5. export function useScreenshot(): UseScreenshot {
  6. const dataUrl = ref<string>("");
  7. const imgType = ref<ImageType>("png");
  8. const error = ref();
  9. async function capture(el: HTMLElement, options: UseScreenshotOptions = {}) {
  10. let data;
  11. const fileName = options.fileName ?? `vue-flow-screenshot-${Date.now()}`;
  12. switch (options.type) {
  13. case "jpeg":
  14. data = await toJpeg(el, options);
  15. break;
  16. case "png":
  17. data = await toPng(el, options);
  18. break;
  19. default:
  20. data = await toPng(el, options);
  21. break;
  22. }
  23. // immediately download the image if shouldDownload is true
  24. if (options.shouldDownload && fileName !== "") {
  25. download(fileName);
  26. }
  27. return data;
  28. }
  29. function toJpeg(
  30. el: HTMLElement,
  31. options: HTMLToImageOptions = { quality: 0.95 }
  32. ) {
  33. error.value = null;
  34. return ElToJpg(el, options)
  35. .then((data) => {
  36. dataUrl.value = data;
  37. imgType.value = "jpeg";
  38. return data;
  39. })
  40. .catch((error) => {
  41. error.value = error;
  42. throw new Error(error);
  43. });
  44. }
  45. function toPng(
  46. el: HTMLElement,
  47. options: HTMLToImageOptions = { quality: 0.95 }
  48. ) {
  49. error.value = null;
  50. return ElToPng(el, options)
  51. .then((data) => {
  52. dataUrl.value = data;
  53. imgType.value = "png";
  54. return data;
  55. })
  56. .catch((error) => {
  57. error.value = error;
  58. throw new Error(error);
  59. });
  60. }
  61. function download(fileName: string) {
  62. const link = document.createElement("a");
  63. link.download = `${fileName}.${imgType.value}`;
  64. link.href = dataUrl.value;
  65. link.click();
  66. }
  67. return {
  68. capture,
  69. download,
  70. dataUrl,
  71. error,
  72. };
  73. }