[canvas Tutorial] Draw a large picture and realize canvas dragging

Show results:

Implementation code:

<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>

other instructions:

1. If you use ts syntax and encounter `Cannot find module...` error when importing pictures, you can add `declare module '*.jpg';` in `*.d.ts` file 

2. The sample code is implemented based on the uniapp framework.

Guess you like

Origin blog.csdn.net/Honiler/article/details/127688682