微信小程序canvas画布自由绘制/画笔功能实现

.wxml

html 复制代码
<canvas class="canvas" type="2d" id="myCanvas" bindtouchstart="get_edit_position" bindtouchmove="brush"/>

定义canvas元素,需要设置type="2d",后续在js可通过Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D对象,用以在画布绘制图形。

bindtouchstart="get_edit_position":用户触摸画布时,获取并更新触摸位置,见以下js部分

bindtouchmove="brush":用户划动画布时,进行自由绘制,见以下js部分

.wxss

定义canvas显示样式,包含宽度、高度、背景色等,也可自定义其他显示样式。

css 复制代码
.canvas{
  background-color: white;
  height: 65vh;
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;  
}

.js

获取画布对象:

将获取的canvas和canvas 2d对象通过this.setData设置为全部变量,后续在其他函数可直接调用。

javascript 复制代码
data:{
    edit_brush:{},
},
onReady() {
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
    .fields({ node: true, size: true })
    .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        this.setData({
            canvas: canvas
            ctx: ctx
        })
    })
},

获取触摸位置:

监听用户触摸画布开始事件,定义自由绘制开始位置

javascript 复制代码
//触摸开始更新初始位置
get_edit_position(e){
    var x = e.touches[0].x*this.data.pixelRatio
    var y = e.touches[0].y*this.data.pixelRatio
    this.setData({
        "edit_brush.x0":x,
        "edit_brush.y0":y
    })
},

自由绘制:

监听用户划动画布事件,不断更新绘制位置进行自由绘制。

javascript 复制代码
//滑动开始自由绘制
brush(e){
    var x = e.touches[0].x*this.data.pixelRatio
    var y = e.touches[0].y*this.data.pixelRatio
    var x0 = this.data.edit_brush.x0
    var y0 = this.data.edit_brush.y0
    var ctx = this.data.ctx //获取的CanvasRenderingContext2D对象
    ctx.beginPath()
    ctx.moveTo(x0,y0)
    ctx.lineTo(x,y)
    ctx.closePath()
    ctx.stroke()
    this.setData({
      'edit_brush.x0':x,
      'edit_brush.y0':y
    })
  }

更多内容欢迎关注博主。

相关推荐
银迢迢2 小时前
微信小程序的开发及问题解决
微信小程序·小程序
liyinchi19882 小时前
原生微信小程序 textarea组件placeholder无法换行的问题解决办法
微信小程序·小程序
说私域4 小时前
基于开源链动2+1模式AI智能名片S2B2C商城小程序的低集中度市场运营策略研究
人工智能·小程序·开源·零售
少恭写代码7 小时前
duxapp 2025-03-29 更新 编译结束的复制逻辑等
react native·小程序·taro
suncentwl8 小时前
答题pk小程序道具卡的获取与应用
小程序·答题小程序·知识竞赛
bysjlwdx8 小时前
uniapp婚纱预约小程序
小程序·uni-app
ALLSectorSorft8 小时前
代驾小程序订单系统框架搭建
小程序·代驾小程序
qq_12498707539 小时前
原生小程序+springboot+vue+协同过滤算法的音乐推荐系统(源码+论文+讲解+安装+部署+调试)
java·spring boot·后端·小程序·毕业设计·课程设计·协同过滤
前端极客探险家18 小时前
微信小程序全解析:从入门到实战
微信小程序·小程序
h_654321018 小时前
微信小程序van-dialog确认验证失败时阻止对话框的关闭
微信小程序·小程序