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

2024-01-09 21:19:20

获取画布信息并绘制背景

.whml

<canvas class="canvas" type="2d" id="myCanvas" 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;  
}

 .js

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

onReady() {
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        this.setData({
          pixelRatio: dpr
        })
        canvas.width = res[0].width * dpr
        canvas.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
        })
        
      })
  },

绘制矩形

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

data:{
    edit_rect:{}
},
draw_basic_rect(){
    ctx.strokeRect(100,100,100,100)
    var t_edit = {
        left_top_x: 100,
        left_top_y: 100,
        width: 100,
        height: 100
    }
    this.setData({
        edit_rect: t_edit,
        current_edit_element: e.currentTarget.dataset.info
    })
    this.draw_rect_edit_icon

文章来源:https://blog.csdn.net/tl437002770/article/details/135485562
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。