微信小遊戲canvas畫布拖動圖片
阿新 • • 發佈:2018-12-31
新手學習,作為筆記。還請高手多多指點,謝謝。
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) } })