uniapp 使用canvas實現圖片拼接(圖片拼版)


<template>
	<view>
		<uni-nav-bar leftIcon="arrowleft" :status-bar="true" fixed="true" color="#ffffff" bgImage="linear-gradient(45deg, #ec008c, #6739b6)"  title="移動開發框架" />
		
		<view class="drawBtn">圖片拼接</view>
		
		<!-- 畫布 -->
		<canvas class='canvas-poster' canvas-id='canvasposter'></canvas>
	</view>
</template>

<script>
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue'
	export default {
		data() {
			return {
				
			}
		},
		components: {
			uniNavBar
		},
		onLoad() {
			
		},
		methods: {
			//繪制到canvas
			viewDrawToCanvas: function() {
				var ctx = uni.createCanvasContext('canvasposter');
				/* 繪制背景*/
				// (矩形左上角的 x 坐標,矩形左上角的 y 坐標 ,矩形的寬度(以像素計) ,矩形的高度(以像素計))
				// 注意因為Id為canvasposter的canvas設置了寬度和高度樣式,兩邊要一致
				// 亦可以設置動態參數實現確保一致
				ctx.rect(0, 0, 794, 1123);
				// 背景填充顏色
				ctx.setFillStyle('white'); 
				// 繪制已填色的矩形
				ctx.fillRect(0, 0, 794, 1123);
				/* 繪制第一張照片*/
				// 參數說明:('圖片路徑',canvas的橫坐標,canvas的縱坐標,圖片的寬度,圖片的寬度)
				ctx.drawImage('圖片路徑', 238, 231, 320, 201);
				/* 繪制第二張照片*/
				ctx.drawImage('圖片路徑', 238, 676, 320, 201);
				uni.showLoading({
					title: '圖片生成中...',
				});			
				ctx.draw(false, this.getTempFilePath);
			},
			//獲取臨時路徑
			getTempFilePath: function() {
				// 當前畫布指定區域的內容導出生成指定大小的圖片,並返回文件路徑
				uni.canvasToTempFilePath({
					canvasId: 'canvasposter',
					success: (res) => {
						console.log(res.tempFilePath)
						this.saveImageToPhotosAlbum(res.tempFilePath)//保存到相冊
					}
				})
			},
			//把生成的圖片保存至相冊
			saveImageToPhotosAlbum: function(imgUrl) {
				uni.hideLoading();
				if (imgUrl) {
					uni.saveImageToPhotosAlbum({
						filePath: imgUrl,
						success: (res) => {
							uni.showToast({
								title: '保存成功',
								icon: 'success',
								duration: 2000
							})
						},
						fail: (err) => {
							uni.showToast({
								title: '保存失敗',
								icon: 'none',
								duration: 2000
							})
						}
					})
				} 
				else {
					uni.showToast({
						title: '繪制中……',
						icon: 'loading',
						duration: 3000
					})
				}
			},
		}
	}
</script>

<style>
	.drawBtn{
		width: 650upx;
		height: 80upx;
		line-height: 80upx;
		text-align: center;
		color: #FFFFFF;
		background-image: linear-gradient(45deg, #ec008c, #6739b6);
		border-radius: 20upx;
		margin: 200upx 50upx;
	}
	
	/* 繪制圖片canvas樣式 */
	.canvas-poster {
		position: fixed;
		width: 794px;
		height: 1123px;
		top: 100%;
		left: 100%;
	}
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM