Canvas

画布扫码体验:

img.jpg

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

注:

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

Screenshot

image

示例代码

  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. })

原文: https://docs.alipay.com/mini/component/canvas