
一、案例描述设计一个小程序演示 canvas 组件的功能和使用方法、canvas 2D 绘图上下文的创建和使用方法。小程序运行后可以在画布上自由绘图还可以清空画布。二、实现思路使用canvas type2d创建 2D 画布分别绑定bind:touchstart和bind:touchmove事件处理函数。在onReady中通过wx.createSelectorQuery().select(#my-canvas).fields({ node: true, size: true }).exec()获取 canvas 节点和尺寸然后canvas.getContext(2d)获取绘图上下文 ctx根据wx.getWindowInfo().pixelRatio计算 dpr设置 canvas 真实像素尺寸并ctx.scale(dpr, dpr)进行坐标系缩放保证高清屏绘图不模糊。paintStart中ctx.moveTo(x, y)移动到起点paintMove中ctx.lineTo(x, y)ctx.stroke()持续描边实现自由绘画。clear中ctx.beginPath()ctx.clearRect(0, 0, canvas.width, canvas.height)清空画布。三、核心代码index.wxmlcanvastype2didmy-canvasbind:touchstartpaintStartbind:touchmovepaintMove/!-- 功能扩展增加颜色切换按钮 --viewclasscolor-layoutviewclasscolor-dot {{strokeColor #ff0000 ? active : }}stylebackground-color:#ff0000data-color#ff0000bind:tapchangeColor红/view!-- 绿/蓝/黑/橙 同理 --/viewviewclassbtn-layoutbuttontypeprimarysizeminibind:tapclear清空画布/button/viewindex.jsPage({data:{strokeColor:#ff0000},onReady(){constquerywx.createSelectorQuery()query.select(#my-canvas).fields({node:true,size:true}).exec((res){constcanvasres[0].nodeconstctxcanvas.getContext(2d)constdprwx.getWindowInfo().pixelRatio canvas.widthres[0].width*dpr canvas.heightres[0].height*dpr ctx.scale(dpr,dpr)this.canvascanvasthis.ctxctx})},// 功能扩展改变画笔颜色changeColor(e){this.setData({strokeColor:e.currentTarget.dataset.color})},paintStart(e){constctxthis.ctx ctx.strokeStylethis.data.strokeColor ctx.lineCaproundctx.lineJoinroundctx.lineWidth5ctx.moveTo(e.touches[0].x,e.touches[0].y)},paintMove(e){constctxthis.ctx ctx.strokeStylethis.data.strokeColor ctx.lineTo(e.touches[0].x,e.touches[0].y)ctx.stroke()},clear(){this.ctx.beginPath()this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}})四、关键知识点canvas type“2d”新版 Canvas 2D 接口通过节点查询获取原生 canvas 对象。高清屏适配canvas 真实像素尺寸 CSS 尺寸 x dpr然后 ctx.scale(dpr, dpr) 让绘制时仍按 CSS 坐标使用。自由绘制touchstart 时 moveTo 起点touchmove 时 lineTo stroke 持续描边lineCap‘round’ lineJoin‘round’ 避免折线生硬。清空画布beginPath() 开新路径clearRect(0, 0, width, height) 区域透明化。五、功能扩展新增一组圆形颜色按钮红/绿/蓝/黑/橙通过>六、总结本案例演示了 canvas 2D 组件完整工作流初始化获取节点 dpr 适配→ 绘制touchstart/touchmove→ 清空并通过颜色切换按钮扩展了画笔颜色在运行时动态改变的能力。