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

8次阅读

共计 2111 个字符,预计需要花费 6 分钟才能阅读完成。

制作钟表分成两部分,一部分是表盘,一部分是时针、分针、秒针的走动,首先,先绘制表盘:
// 绘制表盘
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();

}
结果显示:

源码地址:https://gitee.com/hope93/canv…

正文完
 0