Fabricjs-自定义类型

(function() {
  var canvas = this.__canvas = new fabric.Canvas('c')
  fabric.Object.prototype.transparentCorners = false //设置多边形角的可见性
  var Cross = fabric.util.createClass(fabric.Object, {
    objectCaching: false,
    initialize: function(options) { //初始化 设定一些初始值
      this.callSuper('initialize', options);
      this.animDirection = 'up';
      this.width = 100;
      this.height = 100;
      this.w1 = this.h2 = 100
      this.h1 = this.w2 = 30
    },
    // animateWidthHeight: function() {
    //   var interval = 2
    //   if (this.h2 >= 30 && this.h2 <= 100) {
    //     var actualInterval = (this.animDirection === 'up' ? interval : -interval);
    //     this.h2 += actualInterval
    //     this.w1 += actualInterval
    //   }
    //   if (this.h2 >= 100) {
    //     this.animDirection = 'down'
    //     this.h2 -= interval
    //     this.w1 -= interval

    //   }
    //   if (this.h2 <= 30) {
    //     this.animDirection = 'up'
    //     this.h2 += interval
    //     this.w1 += interval
    //   }
    // },
    _render: function(ctx) {
      //这里通过canvas提供的方法绘制图形
      ctx.fillRect(-this.w1 / 2, -this.h1 / 2, this.w1, this.h1)
      ctx.fillRect(-this.w2 / 2, -this.h2 / 2, this.w2, this.h2)
      ctx.fillStyle = "#adadad"
      // ctx.fillRect(-this.w1 / 6, -this.h1 / 6, this.w1 / 3, this.h1 / 3)
      // ctx.fillRect(-this.w2 / 6, -this.h2 / 6, this.w2 / 3, this.h2 / 3)
      if (this.animDirection === 'up') {
        ctx.scale(0.5, 2)
        ctx.shadowBlur = 20
        ctx.shadowColor = 'blue'
        ctx.fillRect(-this.w1 / 6, -this.h1 / 6, this.w1 / 3, this.h1 / 3)
        ctx.fillRect(-this.w2 / 6, -this.h2 / 6, this.w2 / 3, this.h2 / 3)
      } else {
        ctx.scale(2, 0.5)
        ctx.fillRect(-this.w1 / 6, -this.h1 / 6, this.w1 / 3, this.h1 / 3)
        ctx.fillRect(-this.w2 / 6, -this.h2 / 6, this.w2 / 3, this.h2 / 3)
      }
    }
  })
  canvas.add(
    new Cross({ top: 100, left: 100 }),
    new Cross({ top: 140, left: 230 }),
    new Cross({ top: 300, left: 210 }),
    new Cross({ top: 40, left: 400 }),
    new Cross({ top: 450, left: 400 })
  )

  // setTimeout(function animate() {
  //   canvas.forEachObject(function(obj) {
  //     obj.animateWidthHeight();
  //     obj.dirty = true;
  //   })
  //   canvas.renderAll()
  //   setTimeout(animate, 40)
  // }, 10);
})()

//注释掉的内容和动画效果有关,不影响自定义类型

 

posted @ 2022-04-06 14:46  聂小恶  阅读(267)  评论(1编辑  收藏  举报