微信小游戏canvas画布拖动图片

新手学习,作为笔记。还请高手多多指点,谢谢。

var canvas = wx.createCanvas()
var context = canvas.getContext('2d')
var bgm = wx.createImage()
var hero = wx.createImage()
var x = canvas.width / 2 - 40
var y = canvas.height - 80
//hero初始坐标
bgm.src = 'images/bgm.jpg'
hero.src = 'images/hero.png'
//console.log(x, y)
bgm.onload = function () {
  context.drawImage(bgm, 0, 0)
  //图片加载完成,绘制背景图片
}
hero.onload = function () {
context.drawImage(hero, x, y, 80, 80)
//图片加载完成,绘制hero图片
}
wx.onTouchMove(function (e) {
  var nx = e.touches[0].clientX - 40
  var ny = e.touches[0].clientY - 40

  //获取触摸滑动的坐标
  if (nx > x - 40 && nx < x + 40 && ny > y - 40 && ny < y + 40) {
    //判断触摸坐标是否在图片坐标上

    context.clearRect(0, 0, canvas.width, canvas.height)
    //清空画布
    context.drawImage(bgm, 0, 0)
    context.drawImage(hero, nx, ny, 80, 80)
    //重新绘制图片
    x = nx
    y = ny
    //更新飞机x,y坐标


  }
  else {
    console.log("条件没满足,不能移动", x, y, nx, ny)
  }

})


你可能感兴趣的:(微信小游戏)