Examples of using canvas to save posters in uniapp+vue3, and solutions to various strange problems

We have a requirement here, which is to save the current page as a poster to share with friends or save to a local photo album. Because it is developed on the mini program, the html2canvas library cannot be used, and WeChat officially launched Snapshot The .takeSnapshot API is not very complete yet. If you are purely developing small programs, you can read this article: WeChat small program rendering engine Skyline is a small test - Kuaishu - Zhihu< /span>

I developed it using uniapp, so I can only develop it in the traditional way, which is to use canvas to draw it myself. I encountered many challenges and problems in the process, which I will record here.

Basic canvas configuration

You need to add a canvas to the template and configure the id and canvas-id:

Do not add type="2d" parameters in unnecessary steps, because there will be no response and a lot of problems.

  <!-- 绘制海报的canvas -->
  <canvas class="share-content" id="myCanvas" canvas-id="myCanvas" />

Because my development environment is vue3, there is no need to pass this or instance when creating the canvas and saving the image: 

  // 创建画布:
  const canvasId = "myCanvas"
  const ctx = uni.createCanvasContext(canvasId);

 

Problem: canvasToTempFilePath: fail canvas is empty

1. It may be caused by you adding the parameter type="2d".

2. It may be that the canvas ID or ID is not configured correctly and is not consistent with the ID in js.

3. It may be caused by you starting to use the canvas before it is rendered.

4. It may be caused by you not adding this or instance. This needs to be added to vue2. In vue3, you can use the getCurrentInstance function in vue to obtain the instance object.

import { getCurrentInstance } from "vue";



const instance = getCurrentInstance() as any
// 换整个圆环
const ctx = uni.createCanvasContext("circlefCanvas", instance);

Problem: The drawn picture is blank

1. It may be that after ctx.draw(), you started generating the image without waiting for a while, and it came out blank.

2. It may be that the size of your canvas setting is too small, or the parameters x, y, width and height passed in canvasToTempFilePath are too small, resulting in the content not being drawn or being displayed.

Supongo que te gusta

Origin blog.csdn.net/weixin_44786530/article/details/135002300
Recomendado
Clasificación