linux 电子表小程序,微信小程序Taro开发(3):canvas制作钟表

制作钟表分成两部分,一部分是表盘,一部分是时针、分针、秒针的走动,首先,先绘制表盘:

// 绘制表盘

getDialClock = () => {

const width = this.state.width;

const height = this.state.height;

const ctx = Taro.createCanvasContext('myCanvas', this.$scope);

const R = width/2 - 30;//圆半径

const r = R - 15;

//设置坐标轴原点

ctx.translate(width/2, height/2);

ctx.save();

// 圆心

ctx.beginPath();

ctx.arc(0, 0, 5, 0, 2 * Math.PI, true);

ctx.fill();

ctx.closePath();

// 表盘外圆

ctx.setLineWidth(2);

ctx.beginPath();

ctx.arc(0, 0, R, 0, 2 * Math.PI, true);

ctx.closePath();

ctx.stroke();

// 表盘刻度(大格)

ctx.beginPath();

ctx.setLineWidth(5);

for(var i = 0; i < 12; i++) {

ctx.beginPath();

ctx.rotate(Math.PI / 6);

ctx.moveTo(R, 0);

ctx.lineTo(r, 0);

ctx.stroke();

}

ctx.closePath();

// 表盘刻度(小格)

ctx.beginPath();

ctx.setLineWidth(1);

for(var i = 0; i < 60; i++) {

ctx.beginPath();

ctx.rotate(Math.PI / 30);

ctx.moveTo(R, 0);

ctx.lineTo(R-10, 0);

ctx.stroke();

}

ctx.closePath();

// 表盘时刻(数字)

ctx.beginPath();

ctx.setFontSize(16)//设置字体样式

// ctx.setTextBaseline("middle");//字体上下居中,绘制时间

for(let i = 1; i < 13; i++) {

//利用三角函数计算字体坐标表达式

var x = (r-10) * Math.cos(i * Math.PI / 6 - Math.PI/2);

var y = (r-10) * Math.sin(i * Math.PI / 6 - Math.PI/2);

let sz = i + '';

ctx.fillText(sz, x - 5, y + 5, 15);

}

ctx.closePath();

// 开始绘制

ctx.draw();

}

表盘绘制完毕,再绘制时针,分针,秒针的运动,这里需要新建一个组件来专门管理这个时间运动,在组件中,如下:

// 绘制 针表

drawTime = () => {

const width = this.props.dataRes.width;

const height = this.props.dataRes.height;

const ctx = Taro.createCanvasContext('timeId', this.$scope);

const R = width/2 - 30;//圆半径

//设置坐标轴原点

ctx.translate(width/2, height/2);

ctx.save();

const t = new Date();//获取当前时间

let h = t.getHours();//获取小时

h = h>12?(h-12):h;//将24小时制转化为12小时制

const m = t.getMinutes();//获取分针

const s = t.getSeconds();//获取秒

//绘制时针

ctx.beginPath();

ctx.setStrokeStyle('green')

ctx.setLineWidth(10);

ctx.rotate((Math.PI/6)*(h+m/60+s/3600)-Math.PI/2);

ctx.moveTo(0,0);

ctx.lineTo(R-90,0);

ctx.stroke();

ctx.restore();

ctx.save();

// 绘制分针

ctx.beginPath();

ctx.setStrokeStyle('gold')

ctx.setLineWidth(5);

ctx.rotate((Math.PI/30)*(m+s/3600)-Math.PI/2);

ctx.moveTo(0,0);

ctx.lineTo(R-60,0);

ctx.stroke();

ctx.restore();

ctx.save();

// 绘制秒针

ctx.beginPath();

ctx.setStrokeStyle('red')

ctx.setLineWidth(1);

ctx.rotate((Math.PI/30)*s-Math.PI/2);

ctx.moveTo(0,0);

ctx.lineTo(R-20,0);

ctx.stroke();

ctx.restore();

ctx.save();

ctx.draw();

}

结果显示:

1460000017416486?w=379&h=669

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值