cl-canvas.uvue 1.6 KB

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