效果展示:
实现代码:
<template>
<view>
<canvas
id="gameCanvas"
canvas-id="gameCanvas"
disable-scroll
style="width: 100vw;height: 100vh;"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
></canvas>
</view>
</template>
<script>
import img from '@/static/images/demo.jpg';
export default {
canvasContext: null,
data() {
return {
/** 是否正在绘制 */
drawing: false,
// 画布宽度
width: 0,
// 画布高度
height: 0
}
},
onReady() {
const sys = uni.getSystemInfoSync();
this.width = sys.screenWidth;
this.height = sys.screenHeight;
this.canvasContext = uni.createCanvasContext('gameCanvas');
this.drawImg();
},
methods: {
drawImg() {
var ctx = this.canvasContext;
// 改变坐标系原点
ctx.translate(this.change.x, this.change.y);
// 绘制图片
ctx.drawImage(img, 0, 0, 1500, 1500);
ctx.draw(false, () => {
this.drawing = false
});
},
onTouchStart(e) {
this.start.x = e.touches[0].pageX;
this.start.y = e.touches[0].pageY;
},
onTouchMove(e) {
if(!this.drawing) { // 拦截频繁绘制
this.drawing = true;
let x = this.change.x + e.touches[0].pageX - this.start.x;
let y = this.change.y + e.touches[0].pageY - this.start.y;
// 限制 x、y 拖动范围,禁止滑出边界
x = Math.min(Math.max(x, -1500 + this.width), 0);
y = Math.min(Math.max(y, -1500 + this.height), 0);
if(this.change.x !== x || this.change.y !== y) {
this.change.x = x;
this.change.y = y;
this.drawImg();
this.start.x = e.touches[0].pageX;
this.start.y = e.touches[0].pageY;
} else {
this.drawing = false;
}
}
}
}
}
</script>
其他说明:
1.如使用 ts 语法,在 import 图片时遇 `Cannot find module...` 错误,可在 `*.d.ts` 文件中添加 `declare module '*.jpg';`
2.示例代码是基于 uniapp 框架实现。