一定要有game.js 和game.json文件
game.js中
import './js/libs/weapp-adapter' // 微信官方提供的适配器,主要解决小游戏环境中没有window对象,没有dom和bom结构的尴尬(非底层库)
import './js/libs/symbol'
// import Main from './js/main'
import Test from './js/test'
// new Main()
new Test()
test.js中
let ctx = canvas.getContext('2d')
var image = wx.createImage() // 创建image对象(html中标签)
console.log(image)
export default class Test {
constructor() {
// 普通canvas画图
ctx.fillStyle = 'cyan'
ctx.fillRect(10, 10, 200, 200)
// 重制canvas宽高,不会显示画图结果,但是会影响离屏的尺寸
// canvas.width = 400
// canvas.height = 400
// canvas显示图片,图片的层级会高于canvas画的图形
image.onload = function () {
console.log(image.width, image.height)
ctx.drawImage(image, 0, 0)
}
// image.src = 'https://developers.weixin.qq.com/miniprogram/introduction/image/a.png?t=2018323'
image.src = './images/bg.jpg' // 使用本地图片用从根目录开始的绝对路径,相对路径找不到
// 上屏canvas和离屏canvas
var screenCanvas = wx.createCanvas()
var offScreenCanvas = wx.createCanvas()
var offContext = offScreenCanvas.getContext('2d')
offContext.fillStyle = 'blue'
offContext.fillRect(20, 20, 150, 150)
var screenContext = screenCanvas.getContext('2d')
screenContext.fillStyle = 'green'
screenContext.fillRect(20, 20, 120, 123)
// 上屏canvas和离屏canvas同时存在画图行为时,会类似position: fixed; 按照自定义尺寸定位
ctx.drawImage(offScreenCanvas, 0, 0)
// 事件
wx.onTouchStart(function(e) {
console.log('this is touch start')
console.log(e)
})
wx.onTouchMove(function (e) {
console.log('this is touch move')
console.log(e)
})
wx.onTouchEnd(function (e) {
console.log('this is touch end')
console.log(e)
})
// 来电话等情况下会触发touchCancel事件
wx.onTouchCancel(function (e) {
console.log('this is touch cancel')
console.log('when a phone call come in, this event can be enabled')
console.log(e)
})
console.log(GameGlobal) // 全局对象
GameGlobal.render = function () { // 往全局对象上挂载自定义方法
console.log('this is a render function')
}
render()
var document = {
createElement: function (tagName) {
if(tagName === 'canvas') {
return wx.createCanvas()
} else {
return wx.createImage()
}
}
}
var canvas = document.createElement('canvas')
var images = document.createElement('image')
console.log(canvas)
console.log
var playAudio = { // 小游戏确认支持的音频格式,mp3,aac,wav
playVoice: function () {
var audio = wx.createInnerAudioContext()
audio.src = './audio/bgm.mp3'
// audio.autoplay = true
// audio.loop = true
// audio.obeyMuteSwitch = false
audio.play()
}
}
// playAudio.playVoice()
wx.onShow(function () {
console.log('show')
// playAudio.playVoice()
})
}
}
大致的代码格式就是这样,其他就是游戏流程的设置,和小游戏功能接口的应用,还有h5游戏引擎的应用。