微信小程序 component组件里添加canvas画布

官方文档canvas:https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html

调试基础库:2.9.3

一开始,我使用的是官方文档里的示例代码进行修改的,即

    // js methods内
    drawOn:function(){
    var context = wx.createCanvasContext('firstCanvas')
    context.setStrokeStyle("#00ff00")
    context.setLineWidth(5)
    context.rect(0, 0, 200, 200)
    context.stroke()
    context.setStrokeStyle("#ff0000")
    context.setLineWidth(2)
    context.moveTo(160, 100)
    context.arc(100, 100, 60, 0, 2 * Math.PI, true)
    context.moveTo(140, 100)
    context.arc(100, 100, 40, 0, Math.PI, false)
    context.moveTo(85, 80)
    context.arc(80, 80, 5, 0, 2 * Math.PI, true)
    context.moveTo(125, 80)
    context.arc(120, 80, 5, 0, 2 * Math.PI, true)
    context.stroke()
    context.draw()
    }

发现这个方法无效, wxml略,后查阅官方文档发现component只支持class选择器,是不是不支持canvas-id ?即不支持wx.createCanvasContext(),后换了Canvas 2D的示例代码才成功,如下

/*
    请插入js methods 里
*/

drawOn:function(){
    var query = this.createSelectorQuery()
    /*
      component只支持class索引选择,见
https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
    */
      query.select('.first-canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)
        /* 下面添加canvas 2D代码 */
        ctx.fillRect(0, 0, 100, 100)
    })
    }
<!-- wxml -->
<canvas style="width: 300px; height: 200px;" type="2d" class="first-canvas" bind:tap="drawOn"></canvas>

另:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/RenderingContext.html

  • 通过 Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D 对象,实现了 HTML Canvas 2D Context 定义的属性、方法。
  • 通过 Canvas.getContext('webgl') 或 OffscreenCanvas.getContext('webgl') 接口可以获取 WebGLRenderingContext 对象,实现了 WebGL 1.0 定义的所有属性、方法、常量。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值