cl-canvas.uvue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <view class="cl-canvas">
  3. <canvas
  4. ref="canvasRef"
  5. :id="canvasId"
  6. :style="{ width: width + 'px', height: height + 'px' }"
  7. ></canvas>
  8. </view>
  9. </template>
  10. <script setup lang="ts">
  11. import { onMounted, ref } from "vue";
  12. import { Canvas, useCanvas } from "../../hooks";
  13. import { canvasToPng } from "@/cool";
  14. import { t } from "@/locale";
  15. import { useUi } from "@/uni_modules/cool-ui";
  16. const props = defineProps({
  17. canvasId: {
  18. type: String,
  19. default: ""
  20. },
  21. height: {
  22. type: Number,
  23. default: 300
  24. },
  25. width: {
  26. type: Number,
  27. default: 300
  28. }
  29. });
  30. const emit = defineEmits<{
  31. (e: "load", canvas: Canvas): void;
  32. }>();
  33. const ui = useUi();
  34. // 画布操作实例
  35. const canvas = useCanvas(props.canvasId);
  36. // 画布组件
  37. const canvasRef = ref<UniElement | null>(null);
  38. // 加载画布
  39. function load() {
  40. canvas.create().then(() => {
  41. canvas.height(props.height);
  42. canvas.width(props.width);
  43. emit("load", canvas);
  44. });
  45. }
  46. // 创建图片
  47. async function createImage() {
  48. return canvasToPng(canvasRef.value!);
  49. }
  50. // 预览图片
  51. async function previewImage() {
  52. const url = await createImage();
  53. uni.previewImage({
  54. urls: [url]
  55. });
  56. }
  57. // 保存图片
  58. async function saveImage() {
  59. const url = await createImage();
  60. uni.saveImageToPhotosAlbum({
  61. filePath: url,
  62. success: () => {
  63. ui.showToast({
  64. message: t("保存图片成功"),
  65. type: "success"
  66. });
  67. },
  68. fail: (err) => {
  69. console.error("[cl-canvas]", err);
  70. ui.showToast({
  71. message: t("保存图片失败"),
  72. type: "error"
  73. });
  74. }
  75. });
  76. }
  77. onMounted(() => {
  78. load();
  79. });
  80. defineExpose({
  81. createImage,
  82. saveImage,
  83. previewImage
  84. });
  85. </script>