ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

微信小程序canvas画布实现矩形元素自由缩放、移动功能

2026/10/5 9:44:44 拓冰建站 浏览量
微信小程序canvas画布实现矩形元素自由缩放、移动功能

一、获取画布信息并绘制背景

.whml

<canvas class="canvas" type="2d" id="myCanvas" bindtouchstart="get_rect_touch_position" bindtouchmove="move_or_scale" bind:tap="finish_edit_check"/>

定义canvas元素,需要设置type="2d",后续在js可通过Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D对象,用以在画布绘制图形。

bindtouchstart="get_rect_touch_position":用户触摸画布时,获取并更新触摸位置,见段落四

 bindtouchmove="move_or_scale":用户划动画布时,判断是否是缩放操作或移动操作

bind:tap="finish_edit_check":触摸矩形外部,结束编辑

.wxss

.canvas{background-color: white;height: 65vh;width: 100%;margin-top: 5px;margin-bottom: 5px;  
}

定义canvas显示样式,包含宽度、高度、背景色等,也可自定义其他显示样式。 

 .js

获取画布对象并设置背景图

onReady() {const query = wx.createSelectorQuery()query.select('#myCanvas').fields({ node: true, size: true }).exec((res) => {const canvas = res[0].nodeconst ctx = canvas.getContext('2d')const dpr = wx.getSystemInfoSync().pixelRatiothis.setData({pixelRatio: dpr})canvas.width = res[0].width * dprcanvas.height = res[0].height * dpr      var bg = canvas.createImage()var bg_info = {img: bg,width: canvas.width,height: canvas.height}bg.src = "../../image/白屏竖.png"bg.onload = () =>{ctx.drawImage(bg,0,0,canvas.width,canvas.height)}this.setData({canvas: canvas,ctx: ctx,bg_info: bg_info})})},

将获取的canvas和canvas 2d对象通过this.setData设置为全部变量,后续在其他函数可直接调用。 

二、绘制矩形

可在whml添加按钮或图表,点击后调用绘制矩形函数,作为测试,也可在以上onReady函数获取画布对象后调用绘制矩形函数。