全部产品

canvas 画布

画布。画布是一个矩形区域,用于在页面上绘制图形,开发者可以控制其每一像素。 canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。

相关 API:my.createCanvasContext

扫码体验

image.png

示例代码

<!-- API-DEMO page/component/canvas/canvas.axml -->
<view class="page">
  <view class="canvas-view">
    <canvas 
      id="canvas"
      width="610"
      height="610"
      class="canvas"
      onTouchStart="log"
      onTouchMove="log"
      onTouchEnd="log"
    />
  </view>
</view>
// API-DEMO page/component/canvas/canvas.js
Page({
  onReady() {
    this.point = {
      x: Math.random() * 590,
      y: Math.random() * 590,
      dx: Math.random() * 10,
      dy: Math.random() * 10,
      r: Math.round(Math.random() * 255 | 0),
      g: Math.round(Math.random() * 255 | 0),
      b: Math.round(Math.random() * 255 | 0),
    };
    this.interval = setInterval(this.draw.bind(this), 17);
    this.ctx = my.createCanvasContext('canvas');
  },
  draw() {
    const { ctx } = this;
    ctx.setFillStyle('#FFF');
    ctx.fillRect(0, 0, 610, 610);
    ctx.beginPath();
    ctx.arc(this.point.x, this.point.y, 20, 0, 2 * Math.PI);
    ctx.setFillStyle('rgb(' + this.point.r + ', ' + this.point.g + ', ' + this.point.b + ')');
    ctx.fill();
    ctx.draw();
    this.point.x += this.point.dx;
    this.point.y += this.point.dy;
    if (this.point.x <= 10 || this.point.x >= 590) {
      this.point.dx = -this.point.dx;
      this.point.r = Math.round(Math.random() * 255 | 0);
      this.point.g = Math.round(Math.random() * 255 | 0);
      this.point.b = Math.round(Math.random() * 255 | 0);
    }
    if (this.point.y <= 10 || this.point.y >= 590) {
      this.point.dy = -this.point.dy;
      this.point.r = Math.round(Math.random() * 255 | 0);
      this.point.g = Math.round(Math.random() * 255 | 0);
      this.point.b = Math.round(Math.random() * 255 | 0);
    }
  },
  drawBall() {
  },
  log(e) {
    if (e.touches && e.touches[0]) {
      console.log(e.type, e.touches[0].x, e.touches[0].y);
    } else {
      console.log(e.type);
    }
  },
  onUnload() {
    clearInterval(this.interval);
  },
});
/* API-DEMO page/component/canvas/canvas.acss */
.canvas-view {
  display: flex;
  justify-content: center;
}
.canvas {
  width: 305px;
  height: 305px;
  background-color: #fff;
}

属性

属性名类型默认值描述
idString-组件唯一标识符
styleString--
classString--
widthStringcanvas width attribute-
heightStringcanvas height attribute-
disable-scrollBooleanfalse禁止屏幕滚动以及下拉刷新
onTapEventHandle-点击
onTouchStartEventHandle-触摸动作开始
onTouchMoveEventHandle-触摸后移动
onTouchEndEventHandle-触摸动作结束
onTouchCancelEventHandle-触摸动作被打断,如来电提醒,弹窗
onLongTapEventHandle-长按 500ms 之后触发,触发了长按事件后进行移动将不会触发屏幕的滚动

注意:

  • canvas 标签默认宽度 300px、高度 225px;
  • 同一页面中的 id 不可重复;
  • 如果需要在高 dpr 下取得更细腻的显示,需要先将 canvas 用属性设置放大,用样式缩小,例如
<!-- getSystemInfoSync().pixelRatio === 2 -->
<canvas width="200" height="200" style="width:100px;height:100px;"/>

相关文档