구현을 시작하기 전에 렌더링을 살펴보겠습니다.
팁 1. 네트워크 이미지는 먼저 다운로드 도메인 이름으로 구성되어야 하며, 이는 wx.getImageInfo 통해 임시 경로로 변환될 수 있습니다.
2. 개인적인 습관으로 인해 async-await 구문을 사용하는 데 익숙하므로 regenerator 라이브러리를 소개해야 합니다. 사용 방법은 온라인에서 확인할 수 있습니다.
1. 일반 WeChat API를 캡슐화하여 Promise 객체로 반환합니다./datas/common.js
//WeChat 이미지 정보를 캡슐화합니다. 내보내기 const getWxImageInfo = (imgPath) => { return new Promise((해결, 거부) => { wx.getImageInfo({ src: imgPath, 성공: res => { 해결(res) }, 실패: res => { 거부 (res) } }) })}// 노드 선택기 정보 획득을 캡슐화합니다.export const getSelectQurey = (queryStr) => { return new Promise(resolve => { var query = wx.createSelectorQuery(); query.select(queryStr).boundingClientRect(); query.exec(res => { 해결(res) }) })}// 패키지는 캔버스를 내보내 지정된 크기의 그림을 생성합니다.export const canvasToTempFilePath = (width, height, canvasId, fileType = 'jpg') => { return new Promise((해결, 거부) => { wx.canvasToTempFilePath({ width, height, canvasId, fileType, 성공: res => { 해결(res) }, 실패: res => { 거부(res) } }) })}//이미지를 캡슐화하여 시스템 앨범에 저장합니다. import const saveImageToPhotosAlbum = (filePath) => { return new Promise((해결, 거부) => { wx.saveImageToPhotosAlbum({ filePath, 성공: res => { 해결(res) }, 실패: res => { 거부(res) } }) })} 2. 뷰 구현.wxml
<view class=icon-download catchtap=getCanvas>이미지를 생성하려면 클릭하세요</view><!-- 큰 QR 코드 이미지--><view class='shade' wx:if={{isShowCanvas}}> <view 클래스 ='qr-code'> <canvas class='qr-canvas' canvas-id=qrCanvas id=qrCanvas></canvas> <view class='qr-btn'> <view class='qr-btn-save' catchtap='saveImageToPhotosAlbumFunc'>사진을 저장하고 친구들과 공유하세요</view> <view class='qr-btn-cancel' catchtap='hideCanvas'>취소</view> < /view view> </view></view><!-- QR 코드 대형 이미지.end -->.wxss
/* 큰 이미지 보기*/.shade { width: 100%; height: 100%; background-color: rgba(240, 235, 235, 0.5); position: z-index: 100; : 0;}.qr-code { 너비: 600rpx; 높이: 1000rpx; #fff; 절대; 상단: 50%; 변환: 변환(-50%, -50%); /* 여백: 30rpx auto; ; 여백: 0 자동; 높이: 900rpx;}.qr-btn { 너비: 600rpx; 100rpx; 줄 높이: 100rpx; 색상: #fff; 배경색: #658dc5;}.qr-btn-save { flex: 0 0 500rpx; -정렬: 가운데; 테두리 오른쪽: 1rpx 솔리드 #fff;}.qr-btn-cancel { 텍스트 정렬: 중앙; 0 0 100rpx;} 3. 캔버스를 생성하여 시스템 앨범에 저장팁
제품 이미지는 정사각형이므로 여기 제품 이미지의 너비와 높이는 캔버스 너비를 기준으로 합니다. 이는 단순한 과정일 뿐입니다.
참고: 문서에 wx.canvasToTempFilePath(Object object, Object this) 사용 시 주의해야 할 문장이 있습니다. 현재 캔버스의 지정된 영역의 내용을 내보내어 지정된 크기의 그림을 생성합니다. . draw() 콜백에서 이 메서드를 호출해야만 이미지를 성공적으로 내보낼 수 있습니다.
const app = getApp()const regeneratorRuntime = app.globalData.regeneratorRuntimeconstconst util = require('../../utils/util.js')import { getSelectQurey, getWxImageInfo, canvasToTempFilePath, saveImageToPhotosAlbum} from '../../ datas/common.js'페이지({ 데이터: { isShowCanvas: false, // 캔버스 표시 여부 wxaCode: 'https://xxx..jpg', // 제품 애플릿 코드 goodImageUrl: 'https://xxx..jpg', // 제품 이미지 canvasTempFilePath: '', //캔버스는 이미지를 생성하기 위한 임시 경로를 내보냅니다.}, //생성할 캔버스를 표시하려면 클릭하세요. getCanvas(e) { if (!this.data.wxaCode) { util.showToast('QR 코드 생성 실패'); return; } this.setData({ isShowCanvas: true }, () => { this.createCanvas(); }) }, // 캔버스 숨기기 hideCanvas() { this . setData({ isShowCanvas: false }) }, // 캔버스 생성 async createCanvas() { wx.showLoading({ title: '이미지 생성 중...' }) const _this = this // 노드 선택기 만들기 const res =await getSelectQurey('#qrCanvas') // 캔버스의 너비와 높이 const cvWidth = res[0].width = res[0] .height; const cvSubValue = cvHeight - cvWidth const qrWidth = cvSubValue / 1.5 const qrMargin = (cvSubValue - qrWidth) / 2 const qrX = cvWidth - qrWidth - qrMargin / 2 const qrY = cvWidth + qrMargin const shopNameY = cvWidth + cvSubValue - qrWidth // 임시 경로에 대한 QR 코드 네트워크 이미지 let qrImagePath = ''; { const wxaCode = _this.data.wxaCode; const qrImage = wait getWxImageInfo(wxaCode); qrImagePath = qrImage.path } catch (e) { wx.hideCanvas() util.showToast(); failed'); return; // 제품 네트워크 사진을 임시 경로로 보냅니다. goodsImagePath = '/images/default_goods.png'; const productsImage = _this.data.goodsImageUrl; if (goodsImage) { const goodsImageRes = waitWxImageInfo(goodsImage) goodImagePath =goodsImageRes.path } // 캔버스 생성 wx.createCanvasContext('qrCanvas', _this); // 배경 설정 ctx.setFillStyle('#fff') ctx.fillRect(0, 0, cvWidth, cvHeight); 동일해지려면 ctx.drawImage(goodsImagePath, 0, 0, cvWidth, cvWidth) // QR 코드 이미지 설정 ctx.drawImage(qrImagePath, qrX, qrY, qrWidth, qrWidth); // 상점 이름 설정 const shopName = '나는 상점 이름입니다') ctx.setFontSize(16 ) ctx .setTextAlign('왼쪽') ctx.fillText(상점 이름, 10, shopNameY, cvWidth - qrWidth); // 상품명 텍스트를 포장할 수 없도록 설정합니다. 이것은 단순한 과정일 뿐입니다. const goodName = '이름이 너무 긴 상품은 걱정되실 겁니다.' goodName1 = ''; let goodName2 = '' ctx.setFillStyle('black') ctx.setFontSize(14) ctx.setTextAlign('left') if (goodsName.length <= 10) { ctx.fillText(goodsName, 10, shopNameY + 30, cvWidth - qrWidth) } else if (goodsName.length > 10 && goodsName.length <= 22) { goodsName1 = productsName.substring( 0, 10); 상품이름2 = 상품이름.하위문자열(10); ctx.fillText(goodsName1, 10, shopNameY + 30, cvWidth - qrWidth); ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth) } else {goodsName.substring(0, 10); 상품이름.하위문자열(10, 22) + '...'; ctx.fillText(goodsName1, 10, shopNameY + 30, cvWidth - qrWidth); ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth) } // 팁 설정 consttipText = 'Long 지금 식별 애플릿을 누르고 주문하세요! '; ctx.setFillStyle('gray') ctx.setFontSize(8) ctx.setTextAlign('center') ctx.fillText(tipText, cvWidth / 2, cvHeight - 10) // 완료 ctx.draw(false, () => { wx.hideLoading(); _this.canvasToTempFilePathFunc(cvWidth, cvHeight, 'qrCanvas') }) }, // 현재 캔버스의 지정된 영역의 내용을 내보내 지정된 크기의 그림을 생성합니다. async canvasToTempFilePathFunc(cvWidth, cvHeight, qrCanvas) { try { let res = canvasToTempFilePath( cvWidth, cvHeight, qrCanvas); this.setData({ canvasTempFilePath: res.tempFilePath }); } catch (error) { console.log(error); util.showToast(error.errMsg) } }, // 로컬 비동기 saveImageToPhotosAlbumFunc ( ) { 시도 { 하자 res = 기다리다 saveImageToPhotosAlbum(this.data.canvasTempFilePath); console.log(res); util.showToast('이미지가 성공적으로 저장되었습니다') } catch (err) { console.log(err);주로 나 자신의 편의를 위해 기록하는 것이므로 너무 많은 사용 시나리오를 고려하지 않기 때문에 글은 상대적으로 간단합니다.
요약위 내용은 편집자가 소개한 WeChat 애플릿을 시스템 앨범에 저장한 html5 캔버스 그림입니다. 문의 사항이 있으시면 메시지를 남겨주시면 편집자가 답변해 드리겠습니다. 시간!