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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM