JakartaJS Meetup #4, Feb 25th 2014
We begin drawing the scene by instantiating a Raphaël object. We put two primitive shapes into the Raphaël object. Then we add an attribute to each primitives.
// Creates canvas 320 * 200 at layer "container"
var r = Raphael("container", 320, 200);
// Creates rectangle at x = 10, y = 10, with width 50, height 50
var rect = r.rect(10, 10, 50, 50);
// Creates circle at x = 110, y = 35, with radius 25
var circle = r.circle(110, 35, 25);
// Add a fill color to each primitives
rect.attr({fill: "#45B29D"});
circle.attr({fill: "#DF5A49"});
We can also use paths to draw vector graphics. Basic rules:
var r = Raphael("container", 300, 300);
var curvePath = r.path("M 110 10 s 155 25 40 80 Z");
curvePath.attr({fill:"#EFC94C"});
var customPath = r.path("M 250 250 L 0 -50 L -50 0 L 0 -50 L -50 0 L 0 50 L -50 0 L 0 50 L 150 0 Z");
customPath.attr({
gradient: '90-#EFC94C-#DF5A49',
stroke: '#334D5C', 'stroke-width': 2, 'stroke-linejoin': 'round'
});
Raphaël provides two methods to draw text.
var r = Raphael("container", 600, 100);
var text = r.text(50, 10, "Raphael Rules");
var print = r.print(50, 50, "Raphael Rules", r.getFont("Arial"), 40).attr({fill: "#E27A3F"});
SVG elements can directly subscribe to all the traditional mouse-based events: click, dblclick, mousedown, mousemove, mouseout, mouseover, mouseup, hover.
var r = Raphael(10, 10, 640, 480);
var rect = r.rect(10, 10, 50, 50);
var ellipse1 = r.ellipse(200, 100, 25, 20);
var ellipse2 = r.ellipse(200, 100, 100, 50);
rect.attr({fill: "#DF5A49"});
ellipse1.attr({fill: "#45B29D", stroke: '#DF5A49', 'stroke-width': 2});
ellipse2.attr({stroke: '#334D5C', 'stroke-width': 2});
rect.click(function(evt) {
ellipse1.rotate(36);
ellipse2.rotate(-15);
});
Add custom animations to Raphaël shapes. We can also add easing formulas to the animation, such as: linear, elastic, bounce, easeIn, easeOut, easeInOut, backIn, and backOut.
var paper = Raphael(10, 50, 300, 500);
var circle = paper.circle(150, 40, 30);
circle.attr({fill: "#45B29D", stroke: '#333333'});
var anim = Raphael.animation({cx: 150, cy: 400, opacity: 0.5, "fill": "#DF5A49"}, 2000, "bounce");
circle.animate(anim.repeat(10));