如何使用Raphael.js为图像元素提供“选定”外观

时间:2012-04-03 10:16:00

标签: javascript raphael

我正在使用Raphael.js将图像绘制到画布上。我需要能够选择某些图像元素(我可以这样做)并使它们看起来像是被选中(这就是问题)。

在Raphael.js之前我使用常规的Html5画布和简单的矩形。删除选定的矩形并绘制一个与同一个地方不同颜色的新矩形很简单。

但是现在我正在使用图像,这是一个不同的故事。我正在使用的图片是here。这是一个小小的GIF。

所以问题:

  1. 是否有一种以编程方式更改Raphael.js图像元素颜色的简单方法?
  2. 我可以通过改变其不透明度来使图像元素闪烁吗?
  3. 唯一要求是所选元素必须是可移动的。

    用户点击画布时绘制图像的代码:

    var NodeImage = RCanvas.image("../vci3/images/valaisin.gif", position.x, position.y, 30, 30);           
    NodeImage.toFront();
    RSet.push(NodeImage);
    NodeImage.node.id = 'lamp';
    NodeImage.node.name = name;
    NodeImage.click(function() {
        console.log("Clicked on node " + NodeImage.node.name);  
        // Here should be the code that blinks or changes color or does something else
    });
    

    这是完全不好的主意吗?有没有更好的方法来实现我的目标?

1 个答案:

答案 0 :(得分:3)

我建议授予image一定级别的opacity,并在点击时为其1分配值:

NodeImage.attr('opacity', 0.6);
// ...
NodeImage.click(function() {
    this.attr('opacity', 1);
});

当然,您可能希望管理shape的选定状态,以便稍后关闭所选的样式。实际上,您需要以相同的方式管理所有可选形状,所以让我们这样做:

// keep all selectable shapes in a group to easily manage them
var selectableShapesArray = [NodeImage, otherNodeImage, anotherSelectableShape];

// define the behavior for shape click event
var clickHandler = function() {
    for (var i in selectableShapesArray) {
        var image = selectableShapesArray[i];
        if (image.selected) {
            image.attr('opacity', .6);
            image.selected = false;
            break;
        }
    }
    this.attr('opacity', 1);
    this.selected = true;
}

// attach this behavior as a click handler to each shape
for (var i in selectableShapesArray) {
    var shape = selectableShapesArray[i];
    shape.click(clickHandler);
}​