-Overview of the Canvas API -Demos
Canvas attributes
- width
- height
methods
- getContext()
Context allows for drawing and painting in canvas drawing, images, text, and video processing
Linesf -- add a canvas element to your HTML document -- get context document.getElement('canvas').getContext('2d) -- Draw a line context.beginPath(); context.MoveTo(x, y); context.lineTo(x1,y1) context.strokeStyle(...) context.stroke()
You can perform transformations on the coordinate system
Translate -context.translate(x, y) set new origin for coordinate system Rotate
- context.rotate() Scale
- context.scale() Transform
- context.transform() Arbitary mathematical manipulation of the drawing matrix. 6 arguments define drawing matrix
Gradient gradient = context.createLinearGradient(x, y, width, height) gradient.addColorStop(0, 'color1') gradient.addColorStop(1, 'color2') context.fillStyle = gradient context.fill()
Patterns Basically the same sort of thing
Stash the composite (in a stack) for later context.save()
Set a composite operation for the drawing context.globalCompositeOperation = compositeOperaion;
Go back to normal context.restore();
Scaling
- calculate a scaled width and height for the image
- then context.drawImage() takes image, origin and scale
Filtering
- get image data (from region) data = context.getImageData(x,y,x1,y1)
- data is array of rbga values you can perform an arbitrary transformation on these values
Offscreen canvas
- You can draw the contents of a selection (or something) into an offscreen canvas
- You can then draw the contexts of the offscreen canvas into the visible canvas context.drawImage()
Clipping
- context.beginPath()
- then draw a path
- context.clip(); sets the clipping region to your path
- image is drawn only in the clipping region
You can play video in a canvas (why not?)
- hidden video
- visible canvas
- use context.drawImage() to draw the current video frame into the canvas (in a loop 30fps by using terrible setTimeout())
- demoed desaturation effect
Now you can filter, ciip, transform etc... the video in real time as it plays You could write video editing software.
More demos Not games. There's other cool stuff you can do.
Paint application.
- Canvas is an immediate mode graphics system.
- Draws what you tell it, forgets that it did. SVG and others retain data.
- Fast as a consequence.
Custom controls
- You could have whatever control you like
- Draw it with javascript
Magnifying glass
- Use offscreen canvas to capture magnified region
- Use clipping region to create magnified region
- Write offscreen canvas in to onscreen
You can use these things in any web application (not just games)