微信小程序canvas实例

微信小程序canvas实例

效果展示

wxml

<view class="paint">
    <view class="paintCanvas">
        <canvas canvas-id="paintArea" class="paintArea" bindtouchstart="touchStart"
        bindtouchmove="touchMove" bindtouchend="touchEnd" disable-scroll>
        <!--注意写canvas-id不是id,当然一些id适用的选择器也不能使用--> 
        </canvas>
    </view> 
    <view class="toolsArea">
        <view class="box" bindtap="selectWidth" data-line="2">细</view>
        <view class="box" bindtap="selectWidth" data-line="5">粗</view>
        <view class="box" id="color1" bindtap="selectColor" data-color="black"></view>
        <view class="box" id="color2" bindtap="selectColor" data-color="white"></view>
    </view>
</view>

js

下面是js中data部分代码和绑定事件

data: {
      startX:0,
      startY:0,
      moveX:0,
      moveY:0,
      lineWidth:2,
      lineColor:"#000000",     
    },
    touchStart:function(e){
        this.context=wx.createContext();
        this.setData({
           startX:e.changedTouches[0].x,
           startY:e.changedTouches[0].y,
        });
        this.context.setStrokeStyle(this.data.lineColor);
        this.context.setLineWidth(this.data.lineWidth);
        this.context.setLineCap("round");
        this.context.beginPath();
    },
    touchMove:function(e){      
        this.setData({
            moveX:e.changedTouches[0].x,
            moveY:e.changedTouches[0].y,
        });
        this.context.moveTo(this.data.startX,this.data.startY);
        this.context.lineTo(this.data.moveX,this.data.moveY);
        this.context.stroke();
        this.setData({
            startX:this.data.moveX,
            startY:this.data.moveY
        });
        wx.drawCanvas({
            canvasId:"paintArea",
            reserve:true,
            actions:this.context.getActions(),
        });
    },
    selectWidth:function(e){
        this.setData({
            lineWidth:parseInt(e.currentTarget.dataset.line) 
            /*注意强制转换*/
        });
    },
    selectColor:function(e){
        this.setData({
            lineColor:e.currentTarget.dataset.color
        });
    },

wxss

page{
    height: 100%;
}
/*不配置这个背景色显示可能有问题*/
.paint{
    width: 100%;
    height: 100%;
    position: relative;
}
.paintArea{
    width: 100%;
    height: 100%;
}
.paintCanvas{
    width: 100%;
    height: 100%;
    background-color: lightblue;
}
.toolsArea{
    position: fixed;
    left: 0;
    bottom: 20rpx;
    width: 100%;
    height: 200rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
}
.box{
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    /*50%就是圆了,再大也是*/
    background-color: lightgreen;
    text-align: center;
}
#color1{
    background-color: black;
}
#color2{
    background-color: white;
}
posted @ 2021-01-25 16:03  五仁小奶牛  阅读(1068)  评论(0编辑  收藏  举报