<!--pages/index.wxml--> <view class='box'> <view class='title'>参数绘图</view> <view class='style01'> <canvas canvas-id='myCanvas'></canvas> </view> <view> <form bindsubmit='drawCircle' bindreset='clear'> <input name='x' type='number' placeholder='请输入圆心x坐标'></input> <input name='y' type='number' placeholder='请输入圆心y坐标'></input> <input name='radius' type='number' placeholder='请输入圆的半径'></input> <view class='style02'> <button type='primary' form-type='submit'>画圆</button> <button type='primary' form-type='reset'>清空</button> </view> </form> </view> </view>
/* pages/index.wxss */ .style01 { width: 100%; } canvas { border: 1px solid springgreen; width: 100%; height: 250px; margin-bottom: 20px; } input { margin-bottom: 20px; border-bottom: 1px solid rebeccapurple; } .style02 { display: flex; flex-direction: row; justify-content: center; /* 水平居中对齐 */ margin-top: 20px; } button { width: 25%; margin: 10px; }
// pages/index.js Page({ onLoad: function() { this.ctx = wx.createCanvasContext('myCanvas', this);//创建绘图上下文 }, drawCircle: function(e) { var x = e.detail.value.x; //获取圆心x坐标 var y = e.detail.value.y; //获取圆心y坐标 var radius = e.detail.value.radius;//获取圆半径 this.ctx.arc(x, y, radius, 0, 2 * Math.PI); //创建圆,以x,y为圆心,radius为半径,从0开始绘制,直接绘制一圈,2PI的角度 this.ctx.stroke();//画出当前路径的边框 this.ctx.draw(true);//刷新屏幕(保留画布内容) }, clear: function() { this.ctx.draw();//刷新屏幕(清空画布内容) } })
draw(boolean reserve, function callback)函数
如果 reserve 为 true,则将保留当前画布上的内容继续绘制。