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

更多内容欢迎关注博主。

相关推荐
woshinon5 小时前
【Uniapp(HBuilderX)针对微信小程序和H5平台实现差异化配置(自定义发行)】
微信小程序·小程序·uni-app
hashiqimiya5 小时前
微信小程序---textarea组件布局
微信小程序·小程序
Можно7 小时前
pages.json 和 manifest.json 有什么作用?uni-app 核心配置文件详解
前端·小程序·uni-app
2501_915106327 小时前
iOS 多技术栈混淆实现,跨平台 App 混淆拆解与组合
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张8 小时前
有些卡顿不是 CPU 的问题,还要排查磁盘 I/O
android·ios·小程序·https·uni-app·iphone·webview
a17798877129 小时前
小程序码的生成与获取码中的scene
小程序·c#
CHU7290359 小时前
宠物寄养小程序功能版块设计解析:安全、便捷、透明的寄养服务生态
安全·小程序·宠物
网易独家音乐人Mike Zhou9 小时前
【Python】TXT、BIN文件的十六进制相互转换小程序
python·单片机·mcu·小程序·嵌入式·ti毫米波雷达
AI前端老薛9 小时前
Taro 小程序如何优雅地分包
小程序·taro
蜡台9 小时前
浙政钉(浙里办小程序) H5 二次回退问题修复方案
前端·小程序·浙政钉·浙里办