微信小程序Canvas画简笔画

文章介绍了在微信小程序中使用WXML和JS实现Canvas画布的基本操作,包括初始化canvas、监听触摸事件(paints和paintm)以及处理可能出现的错误提示。

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

1.paint.wxml

<canvas id="canvas" type="2d" bindtouchstart="paints" bindtouchmove="paintm" style="width:{{width}}px;height:{{height}}px;border:1px solid green;"></canvas>

2.paint.js

  data: {
    ctx:'',
    width:350,
    height:500
  },
  onLoad(options) {
    this.canvasinit()
  },

方法:canvasinit()、paints()、paintm()

   canvasinit:function(){
    wx.createSelectorQuery() //此方法等于获取页面所有节点
      .select('#canvas') //类似原生JS的选择器,这里根据id
      .fields({ node: true, size: true })//获取到的节点属性配置,node是否返回实例,size是否返回尺寸大小尺寸
      .exec((res)=>{ //获取之后的回调
        const canvas = res[0].node// Canvas 对象
        const ctx = canvas.getContext('2d')// 渲染上下文
        const renderW = res[0].width
        const renderH = res[0].height
        const dpr = wx.getWindowInfo().pixelRatio
        canvas.width = renderW * dpr
        canvas.height = renderH * dpr
        ctx.scale(dpr,dpr)
        this.setData({
          ctx:ctx,
        })
      })
  },
  paints:function(e){
    let x = e.touches[0].x
    let y = e.touches[0].y
    const ctx = this.data.ctx
    ctx.lineCap = "round"
    ctx.lineJoin = "round"
    ctx.strokeStyle = "#000000"
    ctx.lineWidth = 5
    ctx.moveTo(x,y)
  },
  paintm:function(e){
    let x = e.touches[0].x
    let y = e.touches[0].y
    const ctx = this.data.ctx
    ctx.lineTo(x,y)
    ctx.stroke()
  },

出现错误:Do not have paintm handler in component....或者Do not have pints handler in component....

请检查基础库:基础库为2.21.4或以上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值