【canvas教程】绘制大图并实现画布拖动

效果展示:

实现代码:

<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 框架实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Homilier

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值