uniapp实现横屏签字版

兼容H5、APP、微信小程序
可作为组件直接引入
通过this.$emit(‘tempFilePath’, val.tempFilePath)给予回调
在这里插入图片描述
vue2版本

<template>
	<view class="main-content" v-if="isShow" @touchmove.stop.prevent="">
		<!-- 签字canvas -->
		<canvas 
			class="mycanvas" 
			id="mycanvas" 
			canvas-id="mycanvas" 
			@touchstart="touchstart" 
			@touchmove="touchmove" 
			@touchend="touchend"
		></canvas>
		<!-- 旋转canvas -->
		<canvas
			class="mycanvas"
			:style="{ 'z-index': -1, width: `${screenWidth}px`, height: `${(screenWidth * screenWidth) / screenHeight}px` }"
			id="rotatCanvas"
			canvas-id="rotatCanvas"
		></canvas>
		<cover-view class="button-line">
			<cover-view class="save-button" @tap="finish">保存</cover-view>
			<cover-view class="clear-button" @tap="clear">清除</cover-view>
			<cover-view class="cancel-button" @tap="hide">关闭</cover-view>
		</cover-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			ctx: '', //绘图图像
			points: [], //路径点集合
			isShow: false,
			screenWidth: '',
			screenHeight: ''
		};
	},
	mounted() {
		this.createCanvas();
		uni.getSystemInfo({
			success: e => {
				this.screenWidth = e.screenWidth;
				this.screenHeight = e.screenHeight;
			}
		});
	},
	methods: {
		show() {
			this.clear();
			this.isShow = true;
		},
		hide() {
			this.isShow = false;
		},
		//创建并显示画布
		createCanvas() {
			this.showCanvas = true;
			this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
			//设置画笔样式
			this.ctx.lineWidth = 2;
			this.ctx.lineCap = 'round';
			this.ctx.lineJoin = 'round';
		},
		//触摸开始,获取到起点
		touchstart(e) {
			let startX = e.changedTouches[0].x;
			let startY = e.changedTouches[0].y;
			let startPoint = {
				X: startX,
				Y: startY
			};
			this.points.push(startPoint);
			//每次触摸开始,开启新的路径
			this.ctx.beginPath();
		},
		//触摸移动,获取到路径点
		touchmove(e) {
			let moveX = e.changedTouches[0].x;
			let moveY = e.changedTouches[0].y;
			let movePoint = {
				X: moveX,
				Y: moveY
			};
			this.points.push(movePoint); //存点
			let len = this.points.length;
			if (len >= 2) {
				this.draw(); //绘制路径
			}
		},
		// 触摸结束,将未绘制的点清空防止对后续路径产生干扰
		touchend() {
			this.points = [];
		},
		/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示,必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续,每次从路径集合中区两个点作为起点(moveTo)和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点(即清除第一个点)
			************************************************ */
		draw() {
			let point1 = this.points[0];
			let point2 = this.points[1];
			this.points.shift();
			this.ctx.moveTo(point1.X, point1.Y);
			this.ctx.lineTo(point2.X, point2.Y);
			this.ctx.stroke();
			this.ctx.draw(true);
		},
		//清空画布
		clear() {
			this.ctx.clearRect(0, 0, this.screenWidth, this.screenHeight);
			this.ctx.draw(true);
		},
		//完成绘画并保存到本地
		finish() {
			uni.canvasToTempFilePath(
				{
					canvasId: 'mycanvas',
					success: res => {
						this.rotat(res.tempFilePath);
					},
					complete: com => {}
				},
				this
			);
		},
		// 将图片选装
		rotat(e) {
			let rotatCtx = uni.createCanvasContext('rotatCanvas', this); //创建绘图对象
			// 重新定位中心点
			rotatCtx.translate(0, (this.screenWidth * this.screenWidth) / this.screenHeight);
			// 将画布逆时针旋转90度
			rotatCtx.rotate((270 * Math.PI) / 180);
			// 将签字图片绘制进入Canvas
			rotatCtx.drawImage(e, 0, 0, (this.screenWidth * this.screenWidth) / this.screenHeight, this.screenWidth);
			// 保存后旋转后的结果
			rotatCtx.draw(true);
			setTimeout(() => {
				// 生成图片并回调
				uni.canvasToTempFilePath(
					{
						canvasId: 'rotatCanvas',
						success: val => {
							this.$emit('tempFilePath', val.tempFilePath);
							setTimeout(() => {
								this.hide();
							}, 500);
						},
						complete: com => {
							// console.log(com);
						}
					},
					this
				);
			}, 500);
		}
	}
};
</script>

<style lang="scss" scoped>
.main-content {
	width: 100vw;
	height: 100vh;
	background-color: red;
	position: fixed;
	top: 0rpx;
	left: 0rpx;
	z-index: 9999;
}
.mycanvas {
	width: 100vw;
	height: 100vh;
	background-color: #efefef;
	position: fixed;
	left: 0rpx;
	top: 0rpx;
	z-index: 2;
}
.button-line {
	transform: rotate(90deg);
	position: fixed;
	bottom: 170rpx;
	left: -100rpx;
	width: 340rpx;
	height: 50rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	z-index: 999;
}
.button-style {
	color: #ffffff;
	width: 100rpx;
	height: 60rpx;
	text-align: center;
	line-height: 60rpx;
	border-radius: 10rpx;
}
.save-button {
	@extend .button-style;
	background-color: #02b340;
}
.clear-button {
	@extend .button-style;
	background-color: #ffa500;
}
.cancel-button {
	@extend .button-style;
	background-color: #e10b2b;
}
</style>

vue3+ts版

<script lang="ts" setup>
import { ref, onMounted, nextTick } from "vue";
import type { Ref } from "vue";
const isShow = ref(false);
function open() {
  clear();
  isShow.value = true;
}
function close() {
  isShow.value = false;
}

const ctx = ref(); // 绘图图像
type pointsType = { X: number; Y: number };
const points: Ref<pointsType[]> = ref<pointsType[]>([]); //路径点集合
const screenWidth = ref(0);
const screenHeight = ref(0);
onMounted(() => {
  createCanvas();
  uni.getSystemInfo({
    success: (e) => {
      screenWidth.value = e.screenWidth;
      screenHeight.value = e.screenHeight;
    },
  });
  // nextTick(() => {
  //   show();
  // });
});
//创建并显示画布
function createCanvas() {
  ctx.value = uni.createCanvasContext("mycanvas"); //创建绘图对象
  console.log(ctx);
  //设置画笔样式
  ctx.value.lineWidth = 2;
  ctx.value.lineCap = "round";
  ctx.value.lineJoin = "round";
}
//触摸开始,获取到起点
function touchstart(e: any) {
  let startX = e.changedTouches[0].x;
  let startY = e.changedTouches[0].y;
  let startPoint = {
    X: startX,
    Y: startY,
  };
  points.value.push(startPoint);
  //每次触摸开始,开启新的路径
  ctx.value.beginPath();
}
//触摸移动,获取到路径点
function touchmove(e: any) {
  let moveX = e.changedTouches[0].x;
  let moveY = e.changedTouches[0].y;
  let movePoint = {
    X: moveX,
    Y: moveY,
  };
  points.value.push(movePoint); //存点
  let len = points.value.length;
  if (len >= 2) {
    draw(); //绘制路径
  }
}
// 触摸结束,将未绘制的点清空防止对后续路径产生干扰
function touchend() {
  points.value = [];
}
/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示,必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续,每次从路径集合中区两个点作为起点(moveTo)和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点(即清除第一个点)
			************************************************ */
function draw() {
  let point1 = points.value[0];
  let point2 = points.value[1];
  points.value.shift();
  ctx.value.moveTo(point1.X, point1.Y);
  ctx.value.lineTo(point2.X, point2.Y);
  ctx.value.stroke();
  ctx.value.draw(true);
}
//清空画布
function clear() {
  ctx.value.clearRect(0, 0, screenWidth.value, screenHeight.value);
  ctx.value.draw(true);
}
//完成绘画并保存到本地
function finish() {
  uni.canvasToTempFilePath({
    canvasId: "mycanvas",
    success: (res) => {
      rotat(res.tempFilePath);
    },
    complete: (com) => {},
  });
}
// 将图片选装
function rotat(e: string) {
  let rotatCtx = uni.createCanvasContext("rotatCanvas"); //创建绘图对象
  // 重新定位中心点
  rotatCtx.translate(
    0,
    (screenWidth.value * screenWidth.value) / screenHeight.value
  );
  // 将画布逆时针旋转90度
  rotatCtx.rotate((270 * Math.PI) / 180);
  // 将签字图片绘制进入Canvas
  rotatCtx.drawImage(
    e,
    0,
    0,
    (screenWidth.value * screenWidth.value) / screenHeight.value,
    screenWidth.value
  );
  // 保存后旋转后的结果
  rotatCtx.draw(true);
  setTimeout(() => {
    // 生成图片并回调
    uni.canvasToTempFilePath({
      canvasId: "rotatCanvas",
      success: (val) => {
        emit("callback", val.tempFilePath);
        setTimeout(() => {
          close();
        }, 500);
      },
      complete: (com) => {
        // console.log(com);
      },
    });
  }, 500);
}
const emit = defineEmits(["callback"]);
defineExpose({
  open,
});
</script>
<template>
  <view class="main-content" v-if="isShow" @touchmove.stop.prevent="">
    <!-- 签字canvas -->
    <canvas
      class="mycanvas"
      id="mycanvas"
      canvas-id="mycanvas"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend"
    ></canvas>
    <!-- 旋转canvas -->
    <canvas
      class="mycanvas"
      :style="{
        'z-index': -1,
        width: `${screenWidth}px`,
        height: `${(screenWidth * screenWidth) / screenHeight}px`,
      }"
      id="rotatCanvas"
      canvas-id="rotatCanvas"
    ></canvas>
    <cover-view class="button-line">
      <cover-view class="save-button" @tap="finish">保存</cover-view>
      <cover-view class="clear-button" @tap="clear">清除</cover-view>
      <cover-view class="cancel-button" @tap="close">关闭</cover-view>
    </cover-view>
  </view>
</template>

<style lang="scss" scoped>
.main-content {
  width: 100vw;
  height: 100vh;
  background-color: red;
  position: fixed;
  top: 0rpx;
  left: 0rpx;
  z-index: 9999;
}
.mycanvas {
  width: 100vw;
  height: 100vh;
  background-color: #efefef;
  position: fixed;
  left: 0rpx;
  top: 0rpx;
  z-index: 2;
}
.button-line {
  transform: rotate(90deg);
  position: fixed;
  bottom: 170rpx;
  left: -100rpx;
  width: 340rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 999;
}
.button-style {
  color: #ffffff;
  width: 100rpx;
  height: 60rpx;
  text-align: center;
  line-height: 60rpx;
  border-radius: 10rpx;
}
.save-button {
  @extend .button-style;
  background-color: #02b340;
}
.clear-button {
  @extend .button-style;
  background-color: #ffa500;
}
.cancel-button {
  @extend .button-style;
  background-color: #e10b2b;
}
</style>

生活不易,你我共勉

  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值