微信小程序画布绘制并保存图片

本文介绍了微信小程序中如何利用画布进行图像绘制,包括获取上下文、设置背景色、绘制图像和文字,以及如何将画布内容导出并保存为图片的方法。
摘要由CSDN通过智能技术生成

微信小程序画布绘制

生成上下文
ctx = wx.createCanvasContext('canvasID');

对应的节点信息

<canvas canvas-id="canvasID" 
	class="canvas-one"
	style="width:{
      {
      width}}px;height:{
      {
      height}}px">
 </canvas>

获取对应的手机屏幕的大小

wx.getSystemInfo({
   
    success: res => {
   
        rpx = res.windowWidth/375; // 像素比/iPhone6大小
        this.setData({
   
          width: res.windowWidth,
          height: res.windowHeight
        })
    }
})

canvas 是在一个二维的网格当中,左上角的坐标为(0, 0)

网络图片在画布中不显示的,所以要这样操作,转换成临时图片

wx.getImageInfo({
   
    src: img,
    success: res => {
   
        this
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要保存一个 scroll-view 的截图,需要用到小程序的 canvas 组件。具体步骤如下: 1. 在 wxml 文件中添加 canvas 组件,并设置宽高与 scroll-view 相同: ```html <scroll-view id="scrollView" style="width: 100%; height: 100%;"> <!-- scroll-view 内容 --> </scroll-view> <canvas canvas-id="myCanvas" style="width: 100%; height: 100%; position: fixed; left: -9999px;"></canvas> ``` 2. 在 js 文件中获取 scroll-view 的节点信息和 canvas 的上下文对象: ```javascript const query = wx.createSelectorQuery() const ctx = wx.createCanvasContext('myCanvas') query.select('#scrollView').boundingClientRect() query.exec(res => { const scrollViewRect = res[0] // 设置 canvas 的宽高为 scroll-view 的宽高 const canvasWidth = scrollViewRect.width const canvasHeight = scrollViewRect.height ctx.canvas.width = canvasWidth ctx.canvas.height = canvasHeight }) ``` 3. 绘制 scroll-view 的内容到 canvas 上: ```javascript wx.createSelectorQuery().select('#scrollView').fields({ size: true, scrollOffset: true }).exec(res => { const scrollViewWidth = res[0].width const scrollViewHeight = res[0].height const scrollLeft = res[0].scrollLeft const scrollTop = res[0].scrollTop // 绘制 scroll-view 内容到 canvas 上 ctx.draw(true, () => { wx.canvasToTempFilePath({ x: 0, y: 0, width: scrollViewWidth, height: scrollViewHeight, destWidth: scrollViewWidth * 2, destHeight: scrollViewHeight * 2, canvasId: 'myCanvas', success: res => { // 保存 canvas 截图到本地相册 wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: res => { wx.showToast({ title: '保存成功' }) }, fail: err => { wx.showToast({ icon: 'none', title: '保存失败' }) } }) } }) }) }) ``` 这样就可以将 scroll-view 的内容保存为图片了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值