Raphaël Reference: Drawing Elements on the Canvas



Elements are objects that can be added to a Raphaël canvas. In all examples below, elements are added to a canvas called "paper".

Note that elements are added to the canvas in the order they are defined. The first element defined will appear "below" elements created later.

Shapes and Images

Circles

  • Required Parameters: center x, center y, radius
  • Usage: circle( cx, cy, rad )
  • Example:
    // A circle with center (50,100) and radius 80
    var C = paper.circle( 50, 100, 80 )
    

Ellipses

  • Required Parameters: center x, center y, horizontal radius, vertical radius
  • Usage: ellipse( cx, cy, hrad, vrad )
  • Example:
    // An ellipse with center (50,100), horizontal radius 80, and vertical radius 40
    var E = paper.ellipse( 50, 100, 80, 40 )
    

Images

  • Notes: Used to embed image file to canvas
  • Required Parameters: file name, x, y, width, height
  • Usage: image( "path/file name", x, y, width, height )
  • Example:
    // Inserting image called "myimage.png"
    var Pic = paper.image( "myimage.png", 30, 60, 90, 120 )
    

Rectangles

  • Required Parameters: top left x, top left y, width, height
  • Optional Parameters: corner radius
  • Usage: rect( x, y, width, height, rad )
  • Example:
    // A rectangle with top left corner (50,60), width 100, and height 75
    var R = paper.rect( 50, 60, 100, 75 )
    
    // The same rectangle with rounded corners
    var RR = paper.rect( 50, 60, 100, 75, 8 )
    

Text

Text

  • Required Parameters: center x, center y, string
  • Usage: text( cx, cy, "string" )
  • Example:
    // A message centered at (200, 50)
    var T = paper.text( 200, 50, "Hello World!" )
    

Print

  • Notes: Creates a path element for text
  • Required Parameters: center x, center y, string, font
  • Optional Parameters: font size, origin ("baseline" or "middle"), kerning (value between -1 and 1 that controls letter spacing)
  • Usage: print( cx, cy, "string", paper.getFont( "font" ), size, origin, kerning )
  • Example:
    // A text path 
    var T = paper.print( 200, 50, "Hello World!", paper.getFont( "Times" ), 30, "middle", 0.2 )
    

Paths

  • Notes: Used to construct a continual path or filled polygon, with path string in SVG format
  • Required Parameters: string
  • Usage: path( "SVG string" )
  • Example:
    // A path starting at (40,30), moving to (50,60), moving to (60,90), and ending at (70, 120)
    var P = paper.path( "M 40,30 L 50,60 L 60,90 L 70,120" )
    
    // A closed triangle with vertices (20,50), (50,80), and (40,90)
    var T = paper.path( "M 20,50 L 50,80 L 40,90 Z" )
    

Attributes

Adding Attributes to Elements

    Attributes can be added to any element by appending .attr( { 'attribute-name': 'attribute-value' }) to the name of the element, or just after the definition. Multiple attributes can be listed in the same attribute object.

Positioning Rectangles, Text, and Images

  • Notes: Sets new top left corner of element
  • Options: x, y
  • Usage: element.attr({ 'x': number , 'y': number })
  • Example:
    // A rectangle, originally positioned at (20,30) now located at (60,90)
    var R = paper.rectangle( 20, 30, 25, 30 )
    R.attr({ 'x': 60, 'y': 90 })
    

Positioning Circles

  • Notes: Sets new center of a circle
  • Options: center x, center y
  • Usage: element.attr({ 'cx': number, 'cy': number })
  • Example:
    // A circle, originally positioned at (20,30) now located at (60,90)
    var C = paper.circle( 20, 30, 25 )
    C.attr({ 'cx': 60, 'cy': 90 })
    

Size of Rectangles and Images

  • Options: positive number
  • Usage: element.attr({ 'width': number, 'height': number })
  • Example:
    // A rectangle, originally 30x50, changed to 120x90
    var R = paper.rect( 200, 200, 30, 50 ).attr({ 'width': 120, 'height': 90 })
    

Size of Circles

  • Options: positive number
  • Usage: element.attr({ 'r': number })
  • Example:
    // Changing the radius of a circle
    var C = paper.circle( 60, 60, 20 ).attr({ 'r': 80 })
    
    // Changing the corner radius of a rectangle
    var C = paper.rect( 60, 60, 100, 80 ).attr({ 'r': 7 })
    

Ellipse Radii

  • Elements: ellipses
  • Options: positive numbers
  • Usage: element.attr({ 'rx': number, 'ry': number })
  • Example:
    // An ellipse with horizontal radius 40 and vertical radius 20, change to h radius 30 and v radius 60
    var newE = paper.ellipse( 200, 200, 40, 20 )
    newE.attr({ 'rx': 30, 'ry': 60 })
    

Fill Color

  • Elements: any element or set
  • Notes: Fill an element with a color, image, or gradient
  • Options: rgb, hex, or css color, image, or gradient (as a string)
  • Usage: element.attr({ 'fill': "rgb( r, g, b )" })
  • Example:
    // A red circle
    var redC = paper.circle( 120, 100, 90 ).attr({ 'fill': "rgb( 240, 20, 20 )" })
    
    // A yellow rectangle
    var yellowR = paper.rect( 80, 70, 100, 50 ).attr({ 'fill': 'yellow' })
    
    // A rectangle filled with an image
    var imageR = paper.rect( 80, 70, 100, 50 ).attr({ 'fill': "url('myimage.png')" })
    
    // A circle with a black to blue gradient fill
    var gradC = paper.circle( 250, 100, 90 ).attr({ 'fill': '90-#000000-#0000ff' })
    

Opacity

  • Elements: any element or set
  • Notes: Changes the transparency of an element
  • Options: number between 0 (fully transparent) and 1 (fully opaque)
  • Usage: element.attr({ 'fill-opacity': value })
  • Example:
    // A semi transparent red circle
    var redC = paper.circle( 120, 100, 90 ).attr({ 'fill': 'red', 'fill-opacity': 0.7 })
    

Stroke Color

  • Elements: all elements
  • Options: color in rgb, hex, or css
  • Usage: element.attr({ 'stroke': "color string" })
  • Example:
    // A red stroke on a blue square
    var S = paper.rect( 100, 100, 70, 70 ).attr({ 'fill': 'blue', 'stroke': 'red' })
    

Stroke Opacity

  • Elements: all elements
  • Options: number between 0 (fully transparent) and 1 (fully opaque)
  • Usage: element.attr({ 'stroke-opacity': number })
  • Example:
    // A semi transparent red stroke on a blue square
    var S = paper.rect( 100, 100, 70, 70 ).attr({ 'fill': 'blue', 'stroke': 'red', 'stroke-width': 15, 'stroke-opacity': 0.6 })
    

Stroke Width

  • Elements: all elements
  • Options: positive number
  • Usage: element.attr({ 'stroke-width': number })
  • Example:
    // A thick red stroke on a blue square
    var S = paper.rect( 100, 100, 70, 70 ).attr({ 'fill': 'blue', 'stroke': 'red', 'stroke-width': 10 })
    

Stroke Dash/Dot

  • Elements: all elements
  • Options: type ("", "-", ".", "-.", "-..", ". ", "- ", "--", "- .","--.", "--..")
  • Usage: element.attr({ 'stroke-dasharray': type })
  • Example:
    // A dashed red stroke on a blue square
    var S = paper.rect( 100, 100, 70, 70 ).attr({ 'fill': 'blue', 'stroke': 'red', 'stroke-dasharray': "--." })
    

Stroke Style

  • Elements: all elements
  • Notes: Adjust smoothness of stroke corners and ends (ends apply to paths only)
  • Options: end style ("butt", "square", "round"), corner style ("bevel", "round", "miter")
  • Usage: .attr({ 'stroke-linecap': end style, 'stroke-linejoin': corner style })
  • Example:
    // A rounded red stroke on a blue square
    var S = paper.rect( 100, 100, 70, 70 ).attr({ 'fill': 'blue', 'stroke': 'red', 'stroke-width': 15, 'stroke-linejoin': "round" })
    

Changing Text

  • Elements: text elements
  • Notes: Used to change displayed string
  • Options: string
  • Usage: .attr({ 'text': "string" })
  • Example:
    var T = paper.text( 50, 100, "Hello" ).attr({ 'text': "Goodbye" })
    

Text Anchor

  • Elements: text elements
  • Notes: Used to change alignment of text elements
  • Options: 'start', 'middle' (default), or 'end'
  • Usage: .attr({ 'text-anchor': 'option' })
  • Example:
    // A message starting 50 pixels from the left and centered 100 pixels from the top
    var T = paper.text( 50, 100, "Hello World!" ).attr({ 'text-anchor': 'start' })
    

Font

  • Elements: text
  • Notes: It is recommended that you specify a font family, instead of a single font
  • Options: string with name of preferred font
  • Usage: element.attr({ 'font': "font name" })
  • Example:
    // Text in Arial font, assuming the font is available
    var T = paper.text( 50, 100, "Hello World!" ).attr({ 'font': "Arial" })
    

Font Family

  • Elements: text
  • Usage: element.attr({ 'font-family': "font family name" })
  • Options: string with name of preferred fonts
  • Example:
    // Text in an available font from the specified family
    var T = paper.text( 50, 100, "Hello World!" ).attr({ 'font': "Arial, Helvetica, sans-serif" })
    

Font Size

  • Elements: text
  • Options: number (default 16)
  • Usage: element.attr({ 'font-size': value })
  • Example:
    // Larger text
    var T = paper.text( 50, 100, "Hello World!" ).attr({ 'font-size': 40 })
    

Font Weight

  • Elements: text
  • Options: weight ('normal', 'bold', 'bolder', 'lighter', or a value from 100 to 900)
  • Usage: element.attr({ 'font-weight': weight })
  • Example:
    // Bold text
    var T = paper.text( 50, 100, "Hello World!" ).attr({ 'font-weight': 'bold' })
    

Changing Paths

  • Elements: paths
  • Notes: Used to change an existing path to a new SVG path string
  • Options: SVG path string
  • Usage: element.attr({ 'path': "string" })
  • Example:
    // A path starting at (40,30), moving to (50,60), moving to (60,90), and ending at (70, 120)
    var P = paper.path( "M 40,30 L 50,60 L 60,90 L 70,120" )
    
    // The same path, now ending at (80,100)
    P.attr({ 'path': "M 40,30 L 50,60 L 60,90 L 80,100" })
    

Arrows

  • Elements: paths
  • Notes: Adds an arrow to the start or end of a path
  • Options: type ('classic', 'block', 'open', 'oval', 'diamond'), width ('wide', 'narrow', 'midium'), length ('long', 'midium', 'short')
  • Usage: element.attr({ 'arrow-end': 'type-width-length' })
  • Example:
    // A path with two different arrows at each end
    var P = paper.path( "M 50,50 L 200,200" ).attr({ 'arrow-start': 'open-narrow-short', 'arrow-end': 'diamond-wide-long' })
    

Transform: Translate, Scale, Rotate

  • Elements: any element or set
  • Notes: Does not change x and y attributes of the element, only apparent position
  • Options: string with any combination of eight commands. Use 't value,value', 'r value', 's value', 'm value' for translation, rotation, scale, or matrix transformation in addition to previous transformations. Use 'T', 'R', 'S', 'M' for absolute transformations that ignore previous transformations. Commands can be concatenated into single string.
  • Usage: element.attr({ 'transform': string })
  • Example:
    // Translate a rectangle 200 pixels to the left, 30 pixels down, scale the rectangle by a factor of 1.2, and rotate 45 degrees:
    var r = paper.rect( 20, 20, 60, 60 )
    r.attr({ 'transform': 't200,30s1.2r45' })
    

File Source

  • Elements: images
  • Notes: Change the source file of an image
  • Options: image URL
  • Usage: element.attr({ 'src': "path/file" })
  • Example:
    var Pic = paper.image( "myimage.png", 30, 60, 90, 120 )
    Pic.attr({ 'src': "http://images/newimage.png" })
    

Sets of Elements

  • Notes: A pseudo-element used to operate on several elements at once. Changes to the attributes of a set effect all elements it contains.
  • Usage: set( )
  • Example:
    // Two circles added to a set
    var C1 = paper.circle( 50, 100, 80 )
    var C2 = paper.circle( 150, 200, 30 )
    var S = paper.set()
    
    S.push( C1, C2 )
    

Examples

Random Objects

The canvas below contains several elements: a path element, filled blue, a text element filled in red, and a series of 50 circles created in a for loop with the same center but increasing radii.
<div id="example1" style="text-align:center"> </div> 
<script type="text/javascript"> 
	var paper1 = new Raphael( document.getElementById('example1'), 800, 200 )

	var tetraminoPath = "M 5, 5 L 55, 5 L 55, 55 L 105, 55 L 105, 105 L 55, 105 L 55, 155 L 5, 155 Z"
	var tetramino = paper1.path( tetraminoPath )
		tetramino.attr({ 'stroke': 'black', 'stroke-width':3, 'fill':'blue', 'stroke-dasharray': "--."})
	
	for (i = 0; i < 50; i++ ) {
		paper1.circle( 250, 100, i*2 )
	}
	
	var t = paper1.text( 500, 50, "Welcome to Raphael" ).attr({"font-size": 50, 'fill':'red'})
</script> 

Regular Polygons

The function in the example below generates a regular polygon given a location of its center, the number of sides needed, and the radius of the shape. The example shows the function in use to create several shapes on the canvas.
<div id="example2" style="text-align:center"> </div> 
<script type="text/javascript"> 
	var paper2 = new Raphael( document.getElementById('example2'), 800, 200 )

	function regPoly(x, y, n, s) {	// x,y = center location, n = number of sides, s = radius
    	
    	var path = "", nn, nx, ny, angle;

	    for (nn = 0; nn <= n; nn += 1) {
	        angle = nn / n * 2 * Math.PI;
	        nx = x + Math.cos(angle) * s;
	        ny = y + Math.sin(angle) * s;
	
	        path += (nn === 0 ? "M" : "L") + nx + "," + ny;
	    }
	    return path;
	}
	
	// overlapping triangles:
	paper2.path( regPoly(50, 100, 3, 60) ).attr({ 'fill': 'blue', 'stroke-width':0});
	paper2.path( regPoly(50, 100, 3, 30) ).attr({ 'fill': 'red', 'stroke-width':0, 'opacity':0.6});
	
	paper2.path( regPoly(150, 100, 5, 40) );
	paper2.path( regPoly(250, 100, 8, 30) ).attr({ 'fill': 'green', 'stroke-width':2});
	paper2.path( regPoly(350, 100, 12, 40) ).attr({ 'fill': '#bbb', 'stroke-width':2, 'stroke':'#aa0000'});
	paper2.path( regPoly(450, 100, 16, 30) );
	paper2.path( regPoly(550, 100, 40, 40) ).attr({ 'fill': 'yellow', 'stroke-width':1, 'stroke':'red'});
</script> 

Sine and Cosine

In the example below, curves representing sine and cosine are drawn on a canvas called 'paper1', which is defined to be 800 pixels wide and 200 pixels high.

The difficulty with plotting functions is that the units in the canvas are pixels, which is usually not what we want to work with. For instance, the values of sine and cosine are always between -1 and 1, so if we use these values as our coordinates, the graph will only be two pixels high! Instead, we can "convert" from the canvas units to graph units, and back again. In the example below, I've defined a unit size of 50, meaning that 50 pixels on the screen will represent 1 unit on the number line. The sine and cosine functions take in an x-coordinate (in pixels), convert it using the predefined unit value, calculate sine or cosine using built in functions, then convert this value back into pixels.

Using these functions and a for loop, two curves are created in different ways. The sine curve is created by creating a series of small circles, packed so tightly together that they appear to form a continuous curve. The advantage of this method is that every circle can be a different color, so we're able to gradually change the color within the for loop and create a gradient effect. The cosine curve is created by constructing an SVG path, the building a path element. The advantage with this method is speed - a simple path is much more efficient than hundreds of tiny circles.
<div id="example3" style="text-align:center"> </div> 
<script type="text/javascript"> 
	var paper3 = new Raphael( document.getElementById('example3'), 800, 200 )
	
	var w = 800		// variable to store width, in case we want to adjust later
	var h = 200 	// store height
	var unit = 50	// unit size - 50 pixels will equal a distance of 1
	
	function sine(gx) {			// calculate sine of x (in pixels)
		var x = (gx - w/2)/unit; 	
		var y = Math.sin(x); 
		var gy = h/2 - unit*y; 
		return gy
	}
	
	function cosine(gx){ 		// calculate cosine of x (in pixels)
		var x = (gx - w/2)/unit; 
		var y = Math.cos(x); 
		var gy = h/2 - unit*y; 
		return gy
	}
	
	var numberDots = 600		// number of dots to use in sine curve
	var sinDots = paper3.set()	// create a set to store the dots in the sine curve, in case we want to move or change it
	var cosPath = "M 0,"+cosine(0)		// begin the path for the cosine curve

	for (i = 0; i < numberDots; i++ ) {
		var sinecolor = 'rgb('+(255-i*0.3)+',200,'+(50+i*0.1)+')'		// calculate new fill color
		// create a new dot: 
		var c = paper3.circle( i*w/numberDots, sine( i*w/numberDots ), 3 ).attr({ 'fill': sinecolor,  'stroke-width':0})	
		sinDots.push(c)		// add sine dot to set
		
		cosPath += "L" + i*w/numberDots + "," + cosine( i*w/numberDots )	// add to path for cosine
	}
	
	var cosGraph = paper3.path( cosPath ).attr({ 'stroke': 'red', 'stroke-width':2})	// draw cosine path on canvas
</script>