画布(canvas)。

属性名 类型 默认值 描述
id String - 组件唯一标识符
style String - -
class String - -
width String canvas width attribute -
height String canvas height attribute -
disable-scroll Boolean false 禁止屏幕滚动以及下拉刷新
onTap EventHandle - 点击
onTouchStart EventHandle - 触摸动作开始
onTouchMove EventHandle - 触摸后移动
onTouchEnd EventHandle - 触摸动作结束
onTouchCancel EventHandle - 触摸动作被打断,如来电提醒,弹窗
onLongTap EventHandle - 长按 500ms 之后触发,触发了长按事件后进行移动将不会触发屏幕的滚动

说明

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

图示

canvas - 图1

代码示例

  1. <canvas
  2. id="canvas"
  3. class="canvas"
  4. onTouchStart="log"
  5. onTouchMove="log"
  6. onTouchEnd="log"
  7. />
  1. Page({
  2. onReady() {
  3. this.point = {
  4. x: Math.random() * 295,
  5. y: Math.random() * 295,
  6. dx: Math.random() * 5,
  7. dy: Math.random() * 5,
  8. r: Math.round(Math.random() * 255 | 0),
  9. g: Math.round(Math.random() * 255 | 0),
  10. b: Math.round(Math.random() * 255 | 0),
  11. };
  12. this.interval = setInterval(this.draw.bind(this), 17);
  13. },
  14. draw() {
  15. var ctx = my.createCanvasContext('canvas');
  16. ctx.setFillStyle('#FFF');
  17. ctx.fillRect(0, 0, 305, 305);
  18. ctx.beginPath();
  19. ctx.arc(this.point.x, this.point.y, 10, 0, 2 * Math.PI);
  20. ctx.setFillStyle("rgb(" + this.point.r + ", " + this.point.g + ", " + this.point.b + ")");
  21. ctx.fill();
  22. ctx.draw();
  23. this.point.x += this.point.dx;
  24. this.point.y += this.point.dy;
  25. if (this.point.x <= 5 || this.point.x >= 295) {
  26. this.point.dx = -this.point.dx;
  27. this.point.r = Math.round(Math.random() * 255 | 0);
  28. this.point.g = Math.round(Math.random() * 255 | 0);
  29. this.point.b = Math.round(Math.random() * 255 | 0);
  30. }
  31. if (this.point.y <= 5 || this.point.y >= 295) {
  32. this.point.dy = -this.point.dy;
  33. this.point.r = Math.round(Math.random() * 255 | 0);
  34. this.point.g = Math.round(Math.random() * 255 | 0);
  35. this.point.b = Math.round(Math.random() * 255 | 0);
  36. }
  37. },
  38. drawBall() {
  39. },
  40. log(e) {
  41. if (e.touches && e.touches[0]) {
  42. console.log(e.type, e.touches[0].x, e.touches[0].y);
  43. } else {
  44. console.log(e.type);
  45. }
  46. },
  47. onUnload() {
  48. clearInterval(this.interval)
  49. }
  50. })