When using uniapp to write canvas code, it is displayed normally in the WeChat applet, but when debugging on a real machine, the canvas is always at the top level.
The applet framework and rendering engine are webview. However, in order to optimize the experience, some components such as map, video, textarea, and canvas are implemented through native controls. The native component level is higher than the front-end component (similar to the flash level being higher than div). When I tried to use z-index
solve, it didn't solve the problem.
1. Solution 1
Follow other bloggers' methods of solving the problem, convert uni.canvasToTempFilePath
the call into a picture, and use the picture to render it.
<canvas id="myCanvas" v-if="!canvasSrc" canvas-id="myCanvas" :style="{ width: width + 'px', height: height + 'px' }" class="bg-set"></canvas>
<image :src="canvasSrc" v-if="canvasSrc" :style="{ width: width + 'px', height: height + 'px' }" ></image>
export default {
data() {
return {
ctx: null,
canvasSrc: '',
}
},
methods: {
init(){
//...你的逻辑代码
this.ctx.draw(false, () => {
let self = this;
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function(res) {
self.canvasSrc = res.tempFilePath;
},
})
})
}
}
}
Check the dom structure and find that it is finally displayed in the form of a picture.
There is a bug above. Although it is displayed as a picture, the size of the picture sometimes overflows and sometimes becomes normal.
2. Solution 2
The uni official website provides a solution to use cover-view
labels in canvas.
Note: The default cover-view style is visibility: hidden;
so the DOM tree has a structure, but it cannot be rendered.
We need to set visibility: visible where needed;
to make the page visible
<canvas id="myCanvas" canvas-id="myCanvas" style="width: 200px; height: 200px;" >
<cover-view style="visibility: visible;">
<cover-view class="time">{
{
time}}</cover-view>
</cover-view>
<cover-image class="answer-gif" src="/static/run.gif"></cover-image>
</canvas>
The text in the cover-view tag cannot be automatically wrapped
Solution: Add the following style white-space: pre-wrap to the corresponding cover-view style