【问题标题】:How to add an image to an element as a decorator?如何将图像作为装饰器添加到元素中?
【发布时间】:2014-11-14 02:42:44
【问题描述】:

想象一下,我有一个 Rect 元素,我希望在左上角用一个小的(比如 16x16)PNG 图像来装饰它。我无法确定如何完成该任务。我研究了文档,但(到目前为止)无法找到有关如何完成该任务的示例或参考。是否有人愿意分享食谱或示例指针以帮助我实现目标?

【问题讨论】:

    标签: jointjs


    【解决方案1】:

    更好的是创建自己的自定义形状,其中包含矩形、图像和文本。这为您提供了更大的灵活性,并且您不必为了表达一个形状而拥有两个元素。左上角装饰有小图像的形状可能如下所示:

    joint.shapes.basic.DecoratedRect = joint.shapes.basic.Generic.extend({
    
        markup: '<g class="rotatable"><g class="scalable"><rect/></g><image/><text/></g>',
    
        defaults: joint.util.deepSupplement({
    
            type: 'basic.DecoratedRect',
            size: { width: 100, height: 60 },
            attrs: {
                'rect': { fill: '#FFFFFF', stroke: 'black', width: 100, height: 60 },
                'text': { 'font-size': 14, text: '', 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle', fill: 'black' },
                'image': { 'ref-x': 2, 'ref-y': 2, ref: 'rect', width: 16, height: 16 }
            }
    
        }, joint.shapes.basic.Generic.prototype.defaults)
    });
    

    您可以在图表中这样使用它:

    var decoratedRect = new joint.shapes.basic.DecoratedRect({
        position: { x: 150, y: 80 },
        size: { width: 100, height: 60 },
        attrs: { 
            text: { text: 'My Element' },
            image: { 'xlink:href': 'http://placehold.it/16x16' }
        }
    });
    graph.addCell(decoratedRect);
    

    注意形状是如何指定的,重要的位是 markuptypeattrs 对象,它们通过普通 CSS 选择器引用标记中的 SVG 元素(这里只是标签选择器,但您可以使用类如果你想)。对于图像标签,我们利用 JointJS 特殊属性进行相对定位(refref-xref-y)。使用这些属性,我们将图像相对于rect 元素的左上角定位,并将其从上边缘(ref-y)偏移2px,从左边缘(ref-x)偏移2px。

    注意:type 属性 ('basic.DecoratedRect') 与定义形状的命名空间 (joint.shapes.basic.DecoratedRect) 匹配很重要。这是因为当 JointJS 从 JSON 重新构造图形时,它会查看 type 属性并简单地查找 joint.shapes 命名空间以查看是否为该类型定义了形状。

    【讨论】:

      【解决方案2】:

      我们可以使用以下配方为图像创建元素类型:

      var image = new joint.shapes.basic.Image({
          position : {
              x : 100,
              y : 100
          },
          size : {
              width : 16,
              height : 16
          },
          attrs : {
              image : {
                  "xlink:href" : "images/myImage.png",
                  width : 16,
                  height : 16
              }
          }
      });
      
      graph.addCell(image);
      

      这会将图像定位在 x=100,y=100。重要的是要使尺寸宽/高与 attrs/图像宽/高相匹配,并成为图像本身的宽/高。

      虽然这不会装饰前一个元素,但它可以定位在前一个元素上以达到所需的效果。

      【讨论】:

        猜你喜欢
        • 2013-08-19
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 2018-06-05
        • 1970-01-01
        • 2014-06-01
        相关资源
        最近更新 更多