微信小程序用canvas绘制签名画板

wxml:

<canvas canvas-id="mycanvas" class="mycanvas" bindtouchstart="touchstart" bindtouchmove="touchmove"></canvas>

wxss:

.mycanvas {
    width:750rpx;
    height:800rpx;
    background-color: #ccc;
}

js:

Page({

    /**
     * 页面的初始数据
     */
    data: {
        x: 0,
        y: 0,
        new_x: 0,
        new_x: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

    },
    /**
     * 触摸开始
     */
    touchstart: function(event) {
        const start_x = event.changedTouches[0].x
        const start_y = event.changedTouches[0].y
        this.setData({
            x: start_x,
            y: start_y
        })
    },

    /**
     * 触摸移动
     */
    touchmove: function(event) {
        const move_x = event.changedTouches[0].x
        const move_y = event.changedTouches[0].y
        this.setData({
            new_x: move_x,
            new_y: move_y
        })
        // 调用绘制轨迹
        this.draw_line()
        // 每次移动都重置一次起点,实现任意绘制
        this.data.x = move_x
        this.data.y = move_y
    },
    /**
     * 绘制触摸轨迹
     */
    draw_line: function() {
        const ctx = wx.createCanvasContext("mycanvas")
        // 移动到坐标点
        ctx.moveTo(this.data.x, this.data.y)
        // 坐标点到当前点划线
        ctx.lineTo(this.data.new_x, this.data.new_y)
        ctx.stroke()
        // 参数为true,则保留上一次的绘制内容,默认为false
        ctx.draw(true)
    },

})

效果图展示:
效果图展示-张安金csdn博客

猜你喜欢

转载自blog.csdn.net/weixin_45438997/article/details/106816473