HaaS UI小程序解决方案进阶教学之一:Canvas画图入门

名词解释

AliOS Things: 阿里云智能IoT团队自研的物联网操作系统

HaaS:全称是Hardware as a Service,阿里云智能IoT团队基于AliOS Things系统推出的硬件即服务

HaaS UI:全称是Hardware as a Service User Interface,是源自AliOS Things操作系统上的一套应用&图形解决方案,支持C/C++和 JS两种开发语言

 

Canvas组件

在H5里面,canvas就是一个标签,是一个有特殊功能的标签,实际上它是一个画布,我们可以在这个画布上填各种图形元素,甚至可以操作画布上的每一个像素点。在HaaS UI中,也根据H5中canvas相关的api,内置了一个高性能的canvas组件。关于canvas的api,可参阅:w3c规范,HaaS UI支持了该规范下的大部分api。

 

1、用途

canvas的应用场景非常多,主要运用在一些需要操作图形的场景,如绘制曲线、特效、粒子特效、图表、游戏、二维码、条形码等等场景。

2、开始

在HaaS UI中使用canvas,只需要以下3个步骤即可:

  1. 在template中添加canvas标签
  2. 在组件挂载之后,比方mounted生命周期函数中,获取canvas的上下文环境
  3. 调用context的api进行绘图操作

示例

<template>
  <div class="page">
    <canvas ref="canvas" class="canvas" />
  </div>
</template>
<script>
export default {
  mounted() {
    // 获取canvas context
    let ctx = createCanvasContext(this.$refs.canvas);
    // 绘制红色矩形
    ctx.fillStyle = 'red';
    ctx.fillRect(10, 10, 50, 50);
  },
};
</script>
<style scoped>
.page {
  flex: 1;
  align-items: center;
}
.canvas {
  border-style: solid;
  border-color: #666;
  border-width: 1px;
  background-color: #ccc;
  margin-top: 10px;
}
</style>

image.png

画一朵小花

// 获取canvas context
let ctx = createCanvasContext(this.$refs.canvas);
// 花瓣1
ctx.beginPath();
ctx.arc(100,20,20,0,2*Math.PI);
ctx.fillStyle = 'red';//填充样式
ctx.fill();
// 花瓣2
ctx.beginPath();
ctx.arc(140,20,20,0,2*Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
// 花瓣3
ctx.beginPath();
ctx.arc(100,60,20,0,2*Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
// 花瓣4
ctx.beginPath();
ctx.arc(140,60,20,0,2*Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
//绘制花蕊圆心(120,40)
ctx.beginPath();
ctx.arc(120,40,20,0,2*Math.PI);
ctx.fillStyle = 'yellow';
ctx.fill();
//花径
ctx.beginPath();
ctx.moveTo(120,60);
ctx.quadraticCurveTo(125,130,100,150);//贝塞尔曲线
ctx.stroke();

image.png

3、canvas api

颜色、样式

接口 类型 描述 备注
fillStyle

Color/Gradient

设置填充绘画的样式

ctx.fillStyle="white"|grad

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值