jquery plugin voor canvas tekenen

http://calebevans.me/projects/jcanvas/docs.html#drawBezier
 
$("canvas").drawBezier({ strokeStyle: "#000", strokeWidth: 5, x1: 50, y1: 50, cx1: 200, cy1: 50, cx2: 50, cy2: 150, x2: 200, y2: 150, cx3: 300, cy3: 150, cx4: 150, cy4: 1, x3: 350, y3: 50 })

Docs

Hover over a code snippet to see a demo

jCanvas Object

jCanvas includes a jCanvas object as part of the jQuery object.

$.jCanvas

The jCanvas object contains the following properties/methods:

  • defaults: an object containing jCanvas's default properties
  • prefs: an object containing the same properties as default, except prefs can be modified by the jCanvas function.
  • retrofit: a method to bring back deprecated jCanvas methods.

jCanvas Function

While the jCanvas object stores properties and methods, it is itself a function. For more, see the Preferences section.

Syntax

All methods are regular jQuery methods, and are used in the same manner.

You can call a jCanvas method on any selected canvas object, in which you would usually pass in an object of properties.

$("canvas").drawArc({ fillStyle: "black", x: 100, y: 100, radius: 25 });

jCanvas keeps a set of preferences, which act as defaults for any property not specified.

Properties

These are descriptions of every jCanvas property, their supported methods, and their possible values. Default values are listed first in bold.

align

  • The alignment of the text to be drawn, relative to its x position
  • drawText()
  • "center", "left", "right", "start", "end"

angle

  • The angle at which a polygon is drawn
  • clearCanvas(), drawRect(), drawArc(), drawEllipse(), drawImage(), drawPolygon()
  • 0, any number

baseline

  • The baseline of the text to be drawn, relative to its y position
  • drawText()
  • "middle", "top", "hanging", "alphabetic", "ideographic", "bottom"

projection

  • How much a polygon's sides project in or out (the baseline is 0, so nothing projects)
  • drawPolygon()
  • 0, any integer

ccw

  • If the arc is drawn in the counterclockwise direction
  • drawArc()
  • false, any boolean

closed

  • If the path is closed before it is filled/stroked
  • drawArc(), drawLine(), drawQuad(), drawBezier()
  • false, any boolean

compositing

  • How shapes are drawn on top of one another. For examples on these, visit Mozilla's examples page.
  • All methods
  • "source-over", "source-in", "source-out", "source-atop", "lighter", "destination-over", "destination-in", "destination-out", "destination-atop", "copy", "xor"

cornerRadius

  • The radius of a rectangle's corners
  • drawRect()
  • 0, any number

end

  • The end angle on an arc
  • drawArc()
  • 360, any number

fillStyle

  • The fill color of a shape or path
  • All methods
  • "transparent", any valid color string

font

  • The font of the text to be drawn
  • drawText()
  • "normal 12pt sans-serif", any valid font string

fromCenter

  • If the x and y properties lie at the center point of a shape
  • drawArc(), drawEllipse(), drawRect(), drawImage(), setPixels()
  • true, any boolean

height

  • The height of a shape
  • clearCanvas(), drawEllipse(), drawRect(), drawImage()
  • 0, any number

inDegrees

  • If angles are measured in degrees or radians
  • drawArc(), drawPolygon()
  • true, any boolean

load

  • A callback function to run once an image has loaded
  • pattern(), drawImage()
  • any function

mask

  • Whether the current shape is used to mask future shapes
  • All methods
  • true, any boolean

opacity

  • The opacity of a drawing
  • All methods
  • 1, any number from 0 to 1

r1

  • The start radius of a radial gradient
  • gradient()
  • 10, any number

r2

  • The end radius of a radial gradient
  • gradient()
  • 100, any number

radius

  • The radius of a circle or polygon
  • drawArc(), drawPolygon()
  • 0, any number

repeat

  • How a pattern is repeated
  • pattern()
  • "repeat", "repeat-x", "repeat-y", "no-repeat"

rounded

  • If equal to true, rounds the corners of a path or rectangle
  • drawLine(), drawQuad(), drawBezier()
  • "repeat", "repeat-x", "repeat-y", "no-repeat"

shadowBlur

  • The blur radius of a shadow
  • All methods
  • 3, any number

shadowColor

  • The color of a shadow
  • All methods
  • "transparent", any valid color string

shadowX

  • The X offset of a shadow
  • All methods
  • 0, any number

shadowY

  • The Y offset of a shadow
  • All methods
  • 0, any number

sides

  • How many sides a polygon should have
  • drawPolygon()
  • 3, any number greater than 2

source

  • The source of the image to be drawn.
  • drawImage()
  • "", A valid URL or file reference

start

  • The start angle on an arc
  • drawArc()
  • 0, any number

strokeCap

  • The type of cap for any stroke
  • All methods
  • "butt", "square", "round"

strokeJoin

  • The type of cap between connected strokes
  • All methods
  • "miter", "bevel", "round"

strokeStyle

  • The stroke color of a shape or path
  • All methods
  • "transparent", any valid color string

strokeWidth

  • The stroke width of a shape or path
  • All methods
  • 1, any number

text

  • The text to be drawn
  • drawText()
  • "", any string

width

  • The width of a shape
  • clearCanvas(), drawEllipse(), drawRect(), drawImage()
  • 0, any number

x

  • The x position on the canvas for a shape
  • All methods except drawLine(), drawQuad(), and drawBezier()
  • 0, any number

x1

  • The x position of the first point on a path
  • drawLine(), drawQuad(), drawBezier()
  • 0, any number

y

  • The y position on the canvas for a shape
  • All methods except drawLine(), drawQuad(), and drawBezier()
  • 0, any number

y1

  • The y position of the first point on a path
  • drawLine(), drawQuad(), drawBezier()
  • 0, any number

Preferences

The $.jCanvas() method sets properties of the jCanvas prefs object, so jCanvas methods called in the future can use those properties as defaults.

$.jCanvas({ fillStyle: "green", x: 50, y: 50, radius: 20 }); $("canvas").drawArc()

Reset to Defaults

If nothing is passed, all properties will reset to their original values.

$.jCanvas()

Notes

Any properties included when calling a jCanvas method override their respective defaults.

Compatibility

In the past, jCanvas has deprecated methods in favor of a different method name.

To use these methods with the same name, call the retrofit() method of the jCanvas object.

$.jCanvas.retrofit();

Load Canvas

If nothing is passed, the method returns the canvas's 2D context.

$("canvas").loadCanvas() $("canvas").loadCanvas("2d")

Notes

All methods automatically call load(), so there's no need to call it before using those methods.

Clear Canvas

This method clears all, or any section of the canvas.

Clear Entire Canvas

If nothing is passed, the entire canvas is cleared.

$("canvas").clearCanvas()

Clear a Section

Clearing a section works in the same way as drawing a rectangle, with the rectangle being drawn from its center (by default).

$("canvas") .drawEllipse({ fillStyle: "#000", x: 50, y: 50, width: 200, height: 100, }) .clearCanvas({ x: 50, y: 50, width: 50, height: 50 })

Save Canvas

The saveCanvas() method saves the current state of the canvas.

$("canvas").saveCanvas()

Notes

To revert to the canvas's state before saving, use the restoreCanvas() method.

Restore Canvas

The restoreCanvas() method restores the current state of the canvas.

$("canvas").restoreCanvas()

Translate Canvas

The translateCanvas() method translates the canvas from the included point.

$("canvas").translateCanvas({ x: 100, y: 100 }) .drawRect({ fillStyle: "#000", x: 100, y: 100, width: 100, height: 50 }) .restoreCanvas();

Notes

To revert to the canvas's state before translating, use the restoreCanvas() method.

Rotate Canvas

The rotateCanvas() method rotates the canvas from the included point.

The x and y properties include the center of rotation.

$("canvas").rotateCanvas({ angle: 45, x: 100, y: 100 }) .drawRect({ fillStyle: "#000", x: 100, y: 100, width: 100, height: 50 }) .restoreCanvas();

Notes

To revert to the canvas's state before rotating, use the restoreCanvas() method.

Scale Canvas

The scaleCanvas() method scales the canvas from the included point.

$("canvas").scaleCanvas({ x: 100, y: 100, width: 1.5, height: 1.5 }) .drawArc({ fillStyle: "#000", x: 100, y: 100, radius: 50 }) .restoreCanvas();

Notes

To revert to the canvas's state before scaling, use the restoreCanvas() method.

The width and height values are multiples of the canvas's current width/height (i.e. the original size is 1).

Arcs

$("canvas").drawArc({ strokeStyle: "#000", strokeWidth: 5, x: 100, y: 100, radius: 50, start: 45, end: 135 }) $("canvas").drawArc({ fillStyle: "#000", x: 100, y: 100, radius: 50, start: 0, end: Math.PI, ccw: true, inDegrees: false })

Closed Arc

$("canvas").drawArc({ strokeStyle: "#000", strokeWidth: 5, x: 100, y: 100, radius: 50, start: 30, end: 165, closed: true })

Notes

Angles are measured in degrees by default

The start and end values default to a full circle.

Zero degrees is measured from the top of the arc

Ellipses

You can draw an ellipse using the same basic properties used to draw a rectangle.

$("canvas").drawEllipse({ fillStyle: "#000", x: 150, y: 100, width: 200, height: 100, fromCenter: false })

Rectangles


$("canvas").drawRect({ fillStyle: "#000", x: 50, y: 50, width: 200, height: 100, fromCenter: false })

Rounded Corners

$("canvas").drawRect({ strokeStyle: "#000", strokeWidth: 3, x: 150, y: 100, width: 200, height: 100, cornerRadius: 10, })

Lines

$("canvas").drawLine({ strokeStyle: "#000", strokeWidth: 10, strokeCap: "round", strokeJoin: "miter", x1: 50, y1: 50, x2: 100, y2: 150, x3: 200, y3: 100, x4: 150, y4: 200 })

Rounded Corners

You can round the corners of a line by including the rounded property.

$("canvas").drawLine({ strokeStyle: "#000", strokeWidth: 10, rounded: true, x1: 50, y1: 50, x2: 100, y2: 150, x3: 200, y3: 100, x4: 150, y4: 200 })

Quadratic Curves

Every quadratic curve consists of a start point, a control point (to make the curve), and an end point (which becomes the next start point)

$("canvas").drawQuad({ strokeStyle: "#000", strokeWidth: 5, x1: 50, y1: 50, cx1: 200, cy1: 50, x2: 200, y2: 200 })

Bézier Curves

Every Bézier curve consists of a start point, two control points (to make the curve), and an end point (which becomes the next start point)

$("canvas").drawBezier({ strokeStyle: "#000", strokeWidth: 5, x1: 50, y1: 50, cx1: 200, cy1: 50, cx2: 50, cy2: 150, x2: 200, y2: 150, cx3: 300, cy3: 150, cx4: 150, cy4: 1, x3: 350, y3: 50 })

Text

$("canvas").drawText({ fillStyle: "#729fcf", strokeStyle: "#000", strokeWidth: 5, text: "Hello", align: "center", baseline: "middle", font: "normal 36pt Verdana", x: 150, y: 100 })

Images

If the width or height is left unincluded, that value is calculated.

A callback function may also be run

$("canvas").drawImage({ source: "images/image.jpg", x: 150, y: 150 })

Custom Width/Height

$("canvas").drawImage({ source: "images/image.jpg", x: 50, y: 50, width: 80, height: 100, fromCenter: false })

On Image Load

function arc() { $("canvas").drawArc({ fillStyle: "#000", x: 300, y: 100, radius: 50 }) } $("canvas").drawImage({ source: "images/image.jpg", x: 150, y: 150, load: arc })

Notes

Missing dimensions are calculated proportionally based on the image's original dimensions

Polygons

The drawPolygon() method creates a regular (equal-angled) polygon.

$("canvas").drawPolygon({ fillStyle: "black", x: 200, y: 100, radius: 50, sides: 3, }) $("canvas").drawPolygon({ fillStyle: "#69a", x: 100, y: 100, radius: 50, sides: 5, angle: 25 })

Concave Polygons

To create concave polygons (polygons that point inward), include the projection property.

A value greater than 0 will cause the sides to projection outward. A value less than 0 will cause the sides to projection inward. A value equal to 0 does not project any sides.

$("canvas").drawPolygon({ fillStyle: "#36b", x: 100, y: 100, radius: 50, sides: 5, projection: -0.5 }) $("canvas").drawPolygon({ fillStyle: "#3b6", x: 100, y: 100, radius: 50, sides: 50, projection: 0.1 })

Notes

If the projection property is equal to -1, the polygon will be unable to be seen. Any other numeric value works, though.

Masking

To create a shape which masks other objects, use the mask property.

$("canvas").drawArc({ fillStyle: "#000", x: 150, y: 150, radius: 50, mask: true }) .drawRect({ fillStyle: "#ef2929", x: 100, y: 120, width: 100, height: 100 }) .restoreCanvas();

Notes

To prevent masking of further shapes, call the restoreCanvas() method.

Colors

Color Names

$("canvas").drawArc({ fillStyle: "blue", x: 50, y: 50, radius: 30 })

Hex Values

$("canvas").drawArc({ fillStyle: "#729fcf", x: 50, y: 50, radius: 30 })

RGB Values

$("canvas").drawArc({ fillStyle: "rgb(114, 159, 207)", x: 50, y: 50, radius: 30 })

RGBA Values

$("canvas").drawArc({ fillStyle: "rgba(114, 159, 207, 0.5)", x: 50, y: 50, radius: 30 })

Shadows

$("canvas").drawArc({ fillStyle: "#9cf", shadowColor: "#000", shadowBlur: 5, x: 50, y: 50, radius: 30 })

Offset Position

$("canvas").drawArc({ fillStyle: "#9cf", shadowColor: "#000", shadowBlur: 5, shadowX: 5, shadowY: 5, x: 50, y: 50, radius: 30 })

Gradients

Linear

var linear = $("canvas").gradient({ x1: 0, y1: 0, x2: 0, y2: 100, c1: "#729fcf", s1: 0.33, c2: "#3465a4", s2: 0.67 }); $("canvas").drawArc({ fillStyle: linear, x: 50, y: 50, radius: 30 })

Radial

Radial gradients are created when r1 or r2 is included.

var radial = $("canvas").gradient({ x1: 50, y1: 50, x2: 50, y2: 50, r1: 10, r2: 30, c1: "#729fcf", c2: "#3465a4" }); $("canvas").drawArc({ fillStyle: radial, x: 50, y: 50, radius: 30 })

Notes

Color stops are optional, and are measured from 0 to 1.

Patterns

Calling the pattern() method returns a canvas pattern object, which can be used as a fill or stroke style for any drawing.

function draw(patt) { $("canvas").drawEllipse({ fillStyle: patt, x: 200, y: 100, width: 300, height: 100 }) } var patt = $("canvas").pattern({ source: "images/pattern.jpg", repeat: "repeat", // draw ellipse when pattern loads load: draw })

Notes

By default, the pattern repeats on the x and y axis

Draw Manually

The draw() method is used for quick drawing on the canvas manually (usually using native canvas methods).

The draw() method accepts a function, and the function accepts the canvas context as a parameter.

$("canvas").draw(function(ctx) { ctx.beginPath(); ctx.fillStyle = "#000"; ctx.rect(50, 50, 100, 100); ctx.fill(); ctx.closePath(); })

Notes

The keyword this in the callback function refers to the selected canvas DOM element.

Set Pixels

The setPixels() method allows for modification of a included section of pixels from the canvas.

To modify the pixels, you can loop through each pixel by includeing the each method.

The each callback function accepts 4 color values as parameters (red, green, blue, alpha). It must return an array containing the new values.

function invert() { $("canvas").setPixels({ x: 150, y: 100, width: 100, height: 75, // loop through each pixel each: function(r, g, b, a) { r = 255 - r; g = 255 - g; b = 255 - b; return [r, g, b, a]; } }) } $("canvas").drawImage({ source: "images/image.jpg", x: 150, y: 100, load: invert })

Notes

If the x, y, width, and height properties are not specified, the method loops through the entire canvas's pixels.

Extending jCanvas

Extending jCanvas is as easy as creating a jQuery plugin, as well as a few extra steps to give your plugin full integration with jCanvas.

If you've never created a jQuery plugin, read this first.

Below is a model of how most jCanvas methods are structured:

// jCanvas method $.fn.drawShape = function(args) { // Merge arguments with preferences var params = $.extend({}, $.jCanvas.prefs, args); // Loop through selected elements this.each(function(i, item) { var ctx = $(item).loadCanvas(); // Set the canvas's style properties $.jCanvas.setGlobals(ctx, params); // Your code here }); return this; };

Variables

These variables are necessary to integrate your plugin with jCanvas:

  • args: This should be the one accepted parameter of the plugin. It will eventually contain the properties the user includes when calling the method.
  • params: This merges the current jCanvas preferences with the args object.
  • ctx: The context of the currently iterated canvas

Methods

You may use these jCanvas methods to integrate with existing properties:

  • jCanvas.setGlobals: Sets standard canvas context properties to those from the params variable (like fillStyle) $.jCanvas.setGlobals(ctx, params); // setGlobals() accepts these 2 arguments
  • jCanvas.closePath: Closes a path based on the value of the closed property
  • ctx.beginPath(); ctx.arc(0, 0, 20, 0, Math.PI, false); $.jCanvas.closePath(ctx, params);
  • jCanvas.checkUnits: Returns a numeric value which can be multiplied by an angle value, converting the angle to radians (if it's in degrees)
  • var toRad = $.jCanvas.checkUnits(params); ctx.beginPath(); ctx.arc(0, 0, 5, 45*toRad, (Math.PI)*toRad, false); $.jCanvas.closePath(ctx, params);
  • jCanvas.rotate: Call this before drawing a shape to rotate it based on the value of the angle property
  • $.jCanvas.rotate(ctx, params, shapeWidth, shapeHeight); ctx.fillRect(50, 50, 100, 100); ctx.restore(); This should be called after rotating/drawing, and before jC.closePath() jC.closePath(ctx, params);

Setting Defaults

You can set defaults for your plugin the same way you set jCanvas preferences, except you pass true as a second argument.

$.jCanvas({ myProp: true }, true);

Closures

It's good practice to wrap your jQuery (and jCanvas) plugins in a closure. This makes your code easier to write and more efficient.

(function($, jC) { // Your plugin here }(jQuery, jQuery.jCanvas));

Now, you can reference jQuery as $ and jQuery.jCanvas as jC in your plugin.

Layers

jCanvas allows you to create, maintain, and manipulate layers for any canvas. Each drawing (shape, text, etc.) is its own layer.

To create a new layer, use the jCanvas.addLayer() method, which returns an object formed from merging your arguments with the jCanvas preferences:

To tell jCanvas which method to use, include the fn property.

var myLayer = $.jCanvas.addLayer({ fn: "drawRect", fillStyle: "#37b", x: 100, y: 100, width: 80, height: 40 })

Layers Array

The jCanvas object stores an array containing every jCanvas layer. Anything in the array can later be drawn on a canvas.

$.jCanvas.layers // returns [myLayer]

To put this to use, you can draw these layers on any canvas with jCanvas.drawLayers().

$("canvas").drawLayers() // draws the layers from first to last

So because we created a rectangle object (and therefore, is in the queue), drawLayers() will draw a rectangle on the canvas.s

Example

Here is a complete example of how the jCanvas queue is used:

// Create a rectangle object var myLayer = $.jCanvas.addLayer({ fn: "drawRect", fillStyle: "#37b", x: 100, y: 100, width: 80, height: 40 }); // Draw anything that's in the queue, which in this case, is a rectangle $("canvas").drawLayers();

Whenever you change a property of myLayer and call drawLayers(), the property changes will be reflected when drawing.

Notes

Passing in true as an argument for drawLayers() will clear the canvas before drawing

Animation

Normally, you can animate the properties of an object with the animate() method. Animating drawings on a canvas works (mostly) the same way.

// Create the object of properties var myObj = { fillStyle: "#006", x: 50, y: 50, radius: 50 } // Function to draw circle function draw() { $("canvas") // Canvas must be cleared for every frame .clearCanvas() .drawArc(myObj) } // Draw initial circle draw(); // Animate object properties $(myObj) .delay(250) .animate({ x: 200, y: 150 }, { // Draw every frame duration: 500, step: draw })

Notes

The step property of the second object accepts a callback function, which is run for every frame of the animation. For more information, see the jQuery documentation.