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

.wxml

.wxss

定义画布显示样式

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

.js

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
        })
    })
},

//触摸开始更新初始位置
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
    })
},

//滑动开始自由绘制
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
    })
  }

更多内容欢迎关注博主,小程序功能定制和咨询可私信博主。

你可能感兴趣的:(微信小程序,微信小程序,小程序,canva可画,画布)