how to call raphael methods on jquery objects?

2020-02-29 21:27发布

问题:

I'm creating some circles using Raphael. When a user clicks a button, I want to animate these circles (by growing their radius). How do I do this?

For example, here's my example code:

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="raphael.js"></script>
<script type="text/javascript">

$(function() {  
var paper = new Raphael("canvas_container", 300, 150);
paper.circle(50, 75, 30);
paper.circle(150, 75, 30);

$("button").click(function() {
    $("circle").each(function(i) {      
        this.animate({ r: 100 }, 500); // Doesn't work.
    });     
});

});
</script>
</head>

<body>
<div id="canvas_container"></div>  
<button>Click me to animate the circles</button>
</body>

</html>

[In general, I'm not clear what is the difference between the following two variables:

var c = paper.circle(50, 75, 30); // Raphael circle
$("circle").first(); // using jQuery to grab that Raphael circle

Is the jQuery object a wrapper around the Raphael circle?]

回答1:

Reading through the Raphaël Reference, it seems that you can do this using Raphaël's own Event methods

circle.click(function (event) {
    this.animate({ r: 100 }, 500);
});

The same part of the documentation also notes that you can use libraries like jQuery, but you have to pass in the node, like this:

$(circle.node)

Where circle is the object returned from the paper.circle call.

In your case, however, I think the following code will work:

var paper = new Raphael("canvas_container", 300, 150), 
    circles = [];

circles.push(paper.circle(50, 75, 30));
circles.push(paper.circle(150, 75, 30));

$("button").click(function() {
    $.each(circles, function(i, c){
         c.animate({ r: 100 }, 500);
    });
});


回答2:

Your selector "circle" isn't targeting anything - there's no circle element for you to target. However, you could do this:

circle1 = paper.circle(50, 75, 30); 
circle2 = paper.circle(150, 75, 30); 

$("button").click(function() { 
    circle1.animate({ r: 100 }, 500);
    circle2.animate({ r: 100 }, 500);
}); 

I couldn't tell you if you can animate() the circles based on the radius, but at the very least this gives you a jQuery object to work with.