原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/weixinkaifa/2018/1231/290.html
常州游戏开发运营-用canvas在微信小程序上画时钟教程
最近开始学习canvas,看了慕课网的一个视频,开始自己动手在常州微信小程序开发上画个时钟,
首先我们可以先看以下微信小程序的官方文档:https://mp.weixin.qq.com/debug/wxadoc/dev/api/canvas/reference.html
和canvas的手册对比:http://www.w3school.com.cn/tags/html_ref_canvas.asp
我觉得其实除了删减一些内容之外没什么太大的区别
直接贴代码:
wxml
-
<!--index.wxml--> -
<view class="container"> -
<canvas canvas-id="clock"/> -
</view>
wxss
-
/**index.wxss**/ -
.container { -
height: 100%; -
width: 100%; -
} -
canvas { -
height: 100%; -
width: 100%; -
} -
/*常州网站开发建设有些人会有疑问为什么设置了100%却没有100%,其实要到app.wxss里设置一下*/ -
/**app.wxss**/ -
page{ -
width:100%; -
height:100%; -
}
js
-
Page({ -
data: { -
width: 0, -
height: 0 -
}, -
onLoad: function (options) { -
var that = this -
//获取系统信息 -
wx.getSystemInfo({ -
//获取系统信息成功,将系统窗口的宽高赋给页面的宽高 -
success: function (res) { -
that.width = res.windowWidth -
// console.log(that.width) 375 -
that.height = res.windowHeight -
// console.log(that.height) 625 -
// 这里的单位是PX,实际的常州手游开发手机屏幕有一个Dpr,这里选择iphone,默认Dpr是2 -
} -
}) -
}, -
onReady: function () { -
this.drawClock(); -
// 每40ms执行一次drawClock(),人眼看来就是流畅的画面 -
this.interval = setInterval(this.drawClock, 40); -
}, -
// 所有的canvas属性以及Math.sin,Math.cos()等涉及角度的参数都是用弧度表示 -
// 时钟 -
drawClock: function () { -
const ctx = wx.createCanvasContext('clock'); -
var height = this.height; -
var width = this.width; -
// 设置常州游戏开发培训文字对应的半径 -
var R = width / 2 - 60; -
// 把原点的位置移动到屏幕中间,及宽的一半,高的一半 -
ctx.translate(width / 2, height / 2); -
// 画外框 -
function drawBackground() { -
// 设置线条的粗细,单位px -
ctx.setLineWidth(8); -
// 开始路径 -
ctx.beginPath(); -
// 运动一个圆的路径 -
// arc(x,y,半径,起始位置,结束位置,false为顺时针运动) -
ctx.arc(0, 0, width / 2 - 30, 0, 2 * Math.PI, false); -
ctx.closePath(); -
// 描出点的路径 -
ctx.stroke(); -
}; -
// 画时钟数 -
function drawHoursNum() { -
ctx.setFontSize(20); -
// 圆的起始位置是从3开始的,所以我们手机App外包从3开始填充数字 -
var hours = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]; -
hours.forEach(function (hour, i) { -
var rad = (2 * Math.PI / 12) * i; -
var x = R * Math.cos(rad); -
var y = R * Math.sin(rad); -
// 因为微信小程序不支持BaseLine这个属性,所以这里我们只能自己手动调整位置 -
if (hour == 12) { -
ctx.fillText(hour, x - 11, y + 6); -
} else if (hour == 6) { -
ctx.fillText(hour, x - 5, y + 6); -
} else { -
ctx.fillText(hour, x - 6, y + 6); -
} -
}) -
}; -
// 画数字对应的点 -
function drawdots() { -
for (let i = 0; i < 60; i++) { -
var rad = 2 * Math.PI / 60 * i; -
var x = (R + 15) * Math.cos(rad); -
上篇:上一篇:常州微信公众平台开发-在PhpED中结合Dbg调试
下篇:下一篇:常州微信小程序开发-phpStorm+XDebug+chrome配置



