微信小程序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
    })
  }

更多内容欢迎关注博主。

相关推荐
fxss1 天前
宝宝学识屋有小程序了
微信小程序
拖孩1 天前
又又又用 AI 写了个小程序:我站起来猛蹬 AI,使劲薅羊毛
前端·后端·微信小程序
daguanren1 天前
await nextTick() 之后,页面为什么还没变?读 weapp-vite / Wevu 的三段更新链路
微信小程序·vite
FX1317887KP_2 天前
KET/PET/FCE 口语答案说多长才合适?长度参考与展开方法
小程序·ket口语·pet口语·fce备考·剑桥英语
律宏阔2 天前
微信小程序 + Taro + TanStack Query 缓存与页面返回刷新踩坑实录
前端·微信小程序·taro
千寻技术帮2 天前
微信小程序+Spring Boot 烘焙商城系统(附完整源码+数据库+部署文档)50053
数据库·spring boot·微信小程序·烘焙商城
码云之上3 天前
微信小程序设备指纹实践,删了重装还能认出这台手机吗?
前端·安全·微信小程序
源码手记3 天前
基于微信小程序的相亲交友智能匹配系统-附源码
微信小程序·小程序·交友
源码手记3 天前
基于微信小程序的图书馆座位预约系统(程序+文档)
微信小程序·小程序
aimartec3 天前
企业小程序与APP定制源码买断工程实践:三层解耦架构、状态机防呆与平滑迁移清单
小程序·架构