<template>
<view class="container">
<canvas canvas-id="puzzleCanvas" @touchstart="handleStart" @touchmove="handleMove" @touchend="handleEnd"
@mousedown="handleStart" @mousemove="handleMove" @mouseup="handleEnd"></canvas>
</view>
</template>
<script>
export default {
data() {
return {
ctx: null,
pieces: [
{ x: 0, y: 0, width: 100, height: 100, image: '/static/p1.png' },
{ x: 100, y: 0, width: 100, height: 100, image: '/static/p2.png' },
// 更多拼块
],
currentPiece: null,
offsetX: 0,
offsetY: 0,
isDragging: false
};
},
mounted() {
const canvas = uni.createCanvasContext('puzzleCanvas', this);
this.ctx = canvas;
this.drawPieces();
},
methods: {
drawPieces() {
this.pieces.forEach(piece => {
const img = piece.image;
// 根据路径绘制图片
this.ctx.drawImage(img, piece.x, piece.y, piece.width, piece.height);
});
this.ctx.draw();
},
handleStart(event) {
this.$showlog("点击开始")
const point = this.getPoint(event);
this.currentPiece = this.pieces.find(piece => this.isPointInPiece(point, piece));
this.$showlog("currentPiece",this.currentPiece)
if (this.currentPiece) {
this.offsetX = point.x - this.currentPiece.x;
this.offsetY = point.y - this.currentPiece.y;
this.isDragging = true;
}
},
handleMove(event) {
this.$showlog("点击拖动")
if (this.isDragging && this.currentPiece) {
const point = this.getPoint(event);
this.currentPiece.x = point.x - this.offsetX;
this.currentPiece.y = point.y - this.offsetY;
this.redrawCanvas();
}
},
handleEnd(event) {
this.$showlog("点击结束")
this.isDragging = false;
this.currentPiece = null;
},
getPoint(event) {
this.$showlog("getPoint",event)
const touch = event.touches ? event.touches[0] : event;
return { x: touch.clientX, y: touch.clientY };
},
isPointInPiece(point, piece) {
return (
point.x > piece.x &&
point.x < piece.x + piece.width &&
point.y > piece.y &&
point.y < piece.y + piece.height
);
},
redrawCanvas() {
this.ctx.clearRect(0, 0, 750, 750); // 清空画布,750是canvas的宽度和高度
this.drawPieces();
}
}
}
</script>
<style>
.container {
/* position: relative; */
width: 750rpx;
height: 450rpx;
}
canvas {
width: 750rpx;
height: 450rpx;
background-color: #335566;
}
</style>
代码如上,一个简单的canvas拖动图片的demo,在uniapp内置浏览器中点击图片,出现 了2个奇怪的现象
1、没有拖动,也调用拖动的函数(如图1)
2、明明点击的位置在图片上,而图片的高度是100,得到的clientY=129,明显不对。(如图2)
该代码运行到微信小程序开发者工具,没有上面两个问题。运行改成PC模式也没有上面两个问题