小程序生成海报

注意canvas上面的type=‘2d’

 	<view bindtap="share">点击生成图片</view>
	<canvas class="canvas-exp" type="2d" id="myCanvas" style="width: 750px;height: 493px;border: 1px solid red;"></canvas>
    <view hidden='{{previewHidden}}' class='preview' bindtap="yincang">
        <image src='{{preurl}}' mode='widthFix' class='previewImg' ></image>
        <button bindtap='eventSave' class="btnSave">保存到相册</button>
    </view>

第一步在onload中调用一下方法,canvas画出一个背景图片,在背景图片上加入文字

// An highlighted block
	drawCanvas() {
        let _this = this
        wx.createSelectorQuery().select('#myCanvas').fields({
            node: true,
            size: true
        }).exec((res) => {
            // 获取设备设备像素比
            const dpr = wx.getSystemInfoSync().pixelRatio
            let textCanvas = res[0].node // 重点1
            textCanvas.width = res[0].width * dpr
            textCanvas.height = res[0].height * dpr

            let textCtx = textCanvas.getContext('2d') // 重点2
            /**至此,textCanvas,textCtx已经成功获取到,下面代码为绘图测试代码可忽略**/
            this.setData({
                textCanvas: textCanvas
            })

            //canvas字体自适应
            let xs = wx.getSystemInfoSync().windowWidth / 750

            textCtx.clearRect(0, 0, textCanvas._width, textCanvas._height)
            textCtx.beginPath();
            textCtx.scale(dpr, dpr)

            const bg = textCanvas.createImage()
            bg.src = 'https://6f63-ocr-cf7zl-1302451745.tcb.qcloud.la/zhengshuzhaopian.png?sign=e5b60763e29ee49dfa4a46c80a9c0288&t=1664504332'
            bg.onload = () => {
                textCtx.drawImage(bg, textCanvas._width * 0.02, 0, textCanvas._width * 0.95, textCanvas._height)

                textCtx.save()
                textCtx.font = `normal normal ${14*xs}px SourceHanSerifCN`;
                textCtx.fillStyle = '#000000';

                textCtx.fillText(_this.data.zsXinxi[0].studentName, textCanvas._width * 0.22, textCanvas._height * 0.44);
                textCtx.fillText(_this.data.zsXinxi[0].sex, textCanvas._width * 0.37, textCanvas._height * 0.44);
                textCtx.fillText(_this.data.zsXinxi[0].identity, textCanvas._width * 0.24, textCanvas._height * 0.51);
                textCtx.fillText(_this.data.zsXinxi[0].certificateName, textCanvas._width * 0.24, textCanvas._height * 0.576);
                textCtx.fillText("2022-09-30", textCanvas._width * 0.24, textCanvas._height * 0.64);
                textCtx.fillText("2022", textCanvas._width * 0.705, textCanvas._height * 0.23);
                textCtx.fillText("3", textCanvas._width * 0.77, textCanvas._height * 0.23);
                textCtx.fillText("2022", textCanvas._width * 0.74, textCanvas._height * 0.81);
                textCtx.fillText("9", textCanvas._width * 0.81, textCanvas._height * 0.81);

                textCtx.restore();

                console.log('//')

            }
        })
    },

第二步将画出的生成为图片

	share: function () {
        var that = this
        wx.showLoading({
            title: '努力生成中...'
        })
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: this.data.textCanvas._width,//像素比
            height: this.data.textCanvas._height,
            destWidth: this.data.textCanvas.width*2,
            destHeight: this.data.textCanvas.height*2,
            canvas: this.data.textCanvas,//---------重点(是画布中textCanvas)
            fileType: 'jpg',
            quality: 1,
            success: function (res) {
                that.setData({
                    preurl: res.tempFilePath,
                    previewHidden: false,
                })
                wx.hideLoading()
                console.log("保存图片到相册", res);
            },
            fail(e) {
                wx.hideLoading()
                console.log("失败", e)
            }
        })
    },

第三步将图片保存在系统相册

	eventSave() {
        let that = this
        wx.saveImageToPhotosAlbum({ //保存图片到相册
            filePath: this.data.preurl,
            success: function () {
                wx.hideLoading()
                wx.showToast({
                    title: "保存图片成功!",
                    duration: 2000
                })
                that.setData({
                    previewHidden: true,
                })
            },
            fail() {
                wx.showToast({
                    title: "保存失败!",
                    icon: 'none',
                    duration: 2000
                })
                wx.hideLoading()
            }
        })

    },
### 实现 UniApp 小程序生成海报功能 #### 准备工作 为了在 UniApp 中实现生成海报的功能,需先下载所需的图片资源并将其加载到 Canvas 上。由于小程序的 canvas 组件无法直接使用网络上的图片,因此需要通过 `uni.getImageInfo` API 获取远程图片,并将其路径返回以便后续绘制。 ```javascript // 定义一个异步函数用于下载图片 function urlToFile(url) { return new Promise((resolve, reject) => { uni.getImageInfo({ src: url, success(res) { resolve(res.path); }, fail(err) { console.error('Failed to get image info:', err); uni.showToast({ title: '网络异常', duration: 2000, icon: 'none' }); reject(new Error('Image download failed')); } }); }); } ``` #### 创建 Canvas 并绘制图像 创建一个新的页面,在其中放置 `<canvas>` 标签来作为绘图区域。接着定义 JavaScript 方法用来初始化画布上下文对象以及调用上述定义好的 `urlToFile()` 来获取本地临时文件路径,最后将这些图片按照需求绘制出来。 ```html <template> <view class="container"> <!-- 设置 canvas-id 属性 --> <canvas type="2d" id="posterCanvas"></canvas> <button @click="generatePoster">生成海报</button> </view> </template> <script> export default { methods: { async generatePoster() { const ctx = uni.createCanvasContext('posterCanvas'); try { let imagePath = await urlToFile('https://example.com/image.png'); // 替换成实际 URL ctx.drawImage(imagePath, 0, 0); // (x,y) // 添加更多图形操作... ctx.draw(); } catch(error){ console.error("Error generating poster:", error.message); } } } }; </script> ``` #### 处理 rpx 单位转换 考虑到不同设备屏幕尺寸差异较大,建议采用相对单位如 `rpx` 进行布局设计。当涉及到具体的像素计算时,则可以通过乘以当前窗口宽度除以750的方式完成从 `rpx` 到 px 的转换[^1]。 #### 解决可能出现的问题 有时可能会遇到生成后的海报显示为空白的情况。这可能是由多种因素引起的,比如图片未能成功加载或是绘制顺序不当等问题。对于这类问题,可以参考 Gitee 提供的一个测试项目中的具体解决方案[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值