快应用的canvas 是由canvas组件和渲染脚本组成的
1 canvas 组件
- 不支持属性width 、height ,通过style 设置 width(默认值 0 )和 height(默认值 0 )
- background-color 默认颜色是白色,且设置 background-color 无效
- 只支持 margin 属性,不支持 padding 和 border
1.2 渲染脚本
与 html 类似,通过 getContext 创建 canvas 绘制上下文,但在快应用目前只支持 2d绘制,且须 在
onShow` 生命周期中绘制 canvas。
快应用中绘制canvas 需通过 this.$element() 获取元素绘制,所以必须在元素已经绘制完成的情况下才可以使用,故而要在 onShow 生命周期中使用;当然你也可以使用自定义事件中使用,但必须保证canvas 必须已渲染到页面中。
1.3 示例
示例代码:
<template>
<div class="doc-page">
<div class="content">
<canvas class="new-canvas" id="new-canvas"></canvas>
</div>
</div>
</template>
<style>
.content {
flex-direction: column;
align-items: center;
width: 100%;
}
.new-canvas {
height: 380px;
width: 380px;
}
</style>
<script>
export default {
private: {
drawComplete: false
},
onInit() {
this.$page.setTitleBar({
text: 'canvas简单绘制'
})
},
onShow() {
if (!this.drawComplete) {
this.drawCanvas()
}
},
drawCanvas() {
const canvas = this.$element('new-canvas') //获取 canvas 组件
const ctx = canvas.getContext('2d') //获取 canvas 绘图上下文
//绘制一个矩形
ctx.fillStyle = 'rgb(200,0,0)'
ctx.fillRect(20, 20, 200, 200)
//绘制另一个矩形
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'
ctx.fillRect(80, 80, 200, 200)
this.drawComplete = true
}
}
</script>
效果图展示: