canvas画图并旋转封装组件

本文介绍了一个基于Canvas的微信小程序组件,该组件实现了画图、旋转功能。组件包括.json配置文件,.wxss样式文件,.wxml结构文件和.js逻辑文件。在.wxml中,组件提供了取消、清除和确定三个操作。需要注意的是,canvas在初始化时必须设置宽高,以避免保存时出现问题。在.js文件中,旋转的实现涉及旋转中心的计算和设备像素比(dpr)的处理。dpr决定了屏幕显示尺寸与实际尺寸的比例。在使用该组件时,需在引用页面的.json和.wxml中正确配置组件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组件四大文件:
.json
必须声明component为true

{
  "component": true,
  "usingComponents": {}
}

.wxss文件
这个文件中主要是样式,根据自己所需写就可以了。

.canvas {
  width: 80%;
  height: 100%;
} 

.wxml
这里有三个功能:取消(即退出这个组件),清除(即清除画板),确定(即把你画出来的东西进行保存)
这里有两个canvas,第一个是用来做初始画板的,也就是你在上面画图,第二个是用来做旋转的。不需要旋转的,只写一个canvas就行。踩的一个大坑:初始化时也就是进入组件时一定要给canvas宽高,要不然你在用到canvas的时候再给宽高,那你第一次保存的时候就会出问题。canvas的基本使用看官网。https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html

<canvas class="canvas" id="canvas" canvas-id="canvas" disable-scroll="true" bindtouchstart="canvasStart" bindtouchmove="canvasMove" bindtouchend="canvasEnd" touchcancel="canvasEnd" binderror="canvasIdErrorCallback"></canvas>
  <view class="form-flex">
    <button class="ms-btn-b df-cancel df-clear" bindtap="cancle">
      <text>取消</text>
    </button>
    <button class="ms-btn-b df-cancel" bindtap="cleardraw">
      <text>清除</text>
    </button>
    <button class="ms-btn-b" bindtap='clickMe'>
      <text>确定</text>
    </button>
  </view>
</view>
<canvas id="canvasRotate" canvas-id="canvasRotate" disable-scroll="true" style='width:{{windowHeight}}px;height:{{windowWidth*0.8}}px;position: fixed;left: -3000px;top:-3000px;'></canvas>

.js
第一个canvas的使用时在网上找的,作者叫 前端_李嘉豪 。旋转的难点在于旋转中心和dpr。
旋转中心只会在左上角,旋转角度接收0-360°。
dpr:设备像素比定义了物理像素和设备独立像素的对应关系。通俗一点说就是比如dpr是2,在手机上看就是这么大,比如宽350px,高为600px,实际上把照片导出来看,它其实是700px,1200px。dpr也就是所看到的尺寸跟实际尺寸的比例把。

const app = getApp();
// canvas 全局配置 
var context = null,
  ctx = null;
var isButtonDown = false;
var arrx = [];
var arry = [];
var arrz = [];
var canvasw = 0;
var canvash = 0;
//先获取系统的宽高,给两个canvas宽高
var systemInfo = app.globalData.systemInfo;
var windowWidth = systemInfo.windowWidth;
var windowHeight = systemInfo.windowHeight;
var dpr = systemInfo.pixelRatio;//获取dpr

Component({
  /**
   * 组件的属性
   */
  properties: {
  },
  /**
   * 组件的初始数据
   */
  data: {
    windowWidth: windowWidth,
    windowHeight: windowHeight,
    isDraw: false//用来判断是否对画布进行过操作
  },
  methods: {
    canvasIdErrorCallback: function (e) {
      console.error(e.detail.errMsg)
    },
    //开始
    canvasStart: function (event) {
      isButtonDown = true;
      arrz.push(0);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);

    },
    //过程
    canvasMove: function (event) {
      console.log("moving")
      console.log(context);
      var that = this
      if (isButtonDown) {
        arrz.push(1);
        arrx.push(event.changedTouches[0].x);
        arry.push(event.changedTouches[0].y);
      };

      for (var i = 0; i < arrx.length; i++) {
        if (arrz[i] == 0) {
          context.moveTo(arrx[i], arry[i])
        } else {
          context.lineTo(arrx[i], arry[i])
        };

      };
      
      context.clearRect(0, 0, systemInfo.windowWidth, systemInfo.windowHeight);
      context.setStrokeStyle('#000000');
      context.setLineWidth(4);
      context.setLineCap('round');
      context.setLineJoin('round');
      context.stroke();

      context.draw(false);
      this.setData({
        isDraw: true
      })
    },
    canvasEnd: function (event) {
      isButtonDown = false;
      console.log(event)
    },
    cleardraw: function () {
      //清除画布
      arrx = [];
      arry = [];
      arrz = [];

      context.clearRect(0, 0, windowWidth, windowHeight);//签名画布
      ctx.clearRect(0, 0, windowHeight, windowWidth);//旋转画布清理
      ctx.draw();
      context.draw();
      this.setData({
        isDraw: false
      })
    },
    clickMe: function (e) {
      var that = this;
      if (that.data.isDraw) {
        wx.showLoading({
          title: '正在生成签名',
          mask: true,
        })
        //把第一个canvas生成图片
        wx.canvasToTempFilePath({
          canvasId: 'canvas',
          fileType: 'png',
          success: function (res) {
            console.log(res)
            //生成成功后拿到图片的信息:宽高等
            wx.getImageInfo({
              src: res.tempFilePath,
              success: function (data) {
                console.log(data)
                //成功获取到之后再i用第二个canvas旋转,宽高必须做dpr处理,要不然第一个canvas画出来的图片不能完整地画到第二个canvas上。(注:开发工具上不能模拟dpr,所以不做dpr处理,开发工具是正常的,但是到了手机上就会出问题)
                var imgWidth = data.width / dpr;
                var imgHeight = data.height / dpr;
                
                ctx.clearRect(0, 0, windowHeight, windowWidth);
                ctx.translate(0, imgWidth);//旋转中心,按自己需求
                ctx.rotate(270 * Math.PI / 180);//旋转270°,按自己需求
                ctx.drawImage(res.tempFilePath, 0, 0, imgWidth, imgHeight);
                ctx.draw(true, function () {
                  console.log('draw angin')
                  //再次把canvas生成图片
                  wx.canvasToTempFilePath({
                    canvasId: 'canvasRotate',
                    fileType: 'png',
                    success: function (res) {
                      console.log(res)
                      wx.hideLoading();
                      var path = res.tempFilePath;
                      //这个是和你要使用组件的那个页面相关联的方法,getGuid 是写在那个页面的方法,{path}是要传过去的参数
                      that.triggerEvent('getGuid', { path })
                      that.cleardraw();
                    },
                    fail: function (res) {
                      app.msg('')
                    }
                  }, that);
                });
              }
            })

          },
          fail: function (res) {
            app.msg('')
          }
        }, that)
      } else {
        app.msg('');
      }
    },
    //点击取消
    cancle: function () {
      var path = 'canSignature';
      this.setData({
        isDraw: false
      })
      this.cleardraw();
      this.triggerEvent('getGuid', { path })
    },
  },
  //进入组件,会先加载这个方法,两个canvas要在这里获取
  ready: function () {
    console.log(this);

    ctx = wx.createCanvasContext('canvasRotate', this);
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas', this);
    context.beginPath();
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');

    context.draw();

    console.log('context');
    console.log(context)
  }
})


需要用到组件的页面
.json
需要写明组件的路径

{
  "usingComponents": {
    "signature": "/pages/pages/components/signature/signature"
  }
}

.wxml

//进入组件的按钮
<image  src="min.png" class="" bindtap='clickSignature'></image>
//插入组件,链接组件的方法写在这
<signature class='{{canSignature ? "show" : "hide"}}' id='signature' bind:getGuid='getGuid'></signature>

.js

//点击进入组件
  clickSignature: function() {
    this.setData({
      canSignature: true
    })
  },
  //这个方法根据自己需要去写
  getGuid: function(e) {
  //e就是从组件传过来的东西
    console.log(e);
    var that = this;
    var path = e.detail.path;
    if (path == 'canSignature') {
      that.setData({
        canSignature: false,
      })
    } else {
      that.setData({
        canSignature: false,
      })
      
    }
  },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值