CANVAS




What is it all about?

CANVAS is a way of doing graphics, using JavaScript, in HTML 5. You specify a field with the CANVAS tag, in which you insert what you drew when running the JavaScriptet. It is essentially the same as using a JavaScript for writing in a field as shown here.

You can combine CANVAS with other images, so you have a background image, e.g. the HTML Shark, and e.g. a small circle to mark something:

You browser does not suppert the HTML5 CANVAS tag.


Programs are available that can convert images, e.g. jpg to CANVAS, but in practice it is a bad idea. The shark logo on this page, for instance, takes up 39709 lines of code.


The CANVAS tag

The CANVAS tag used for the graphics is really just a container like the ones we know from frames, i.e. you can specify size, background color, borders, etc. The content you draw, you specify using a JavaScript after the container, e.g. a circle:

<CANVAS ID="CircleCanvas" WIDTH="150" HEIGHT="150" STYLE="border:1px solid #000000">
</CANVAS>

<SCRIPT>
window.onload = function() {
var canvas = document.getElementById("CircleCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(75,75,30,0,2*Math.PI);
ctx.strokeStyle = "green";
ctx.lineWidth = 3;
ctx.stroke();
};
</SCRIPT>

On screen, it looks like this:



One of the places where things can go wrong using CANVAS is the specification of the size of the image. Normally the recommendation for specifying size is the attribute STYLE instead of the attributes HEIGHT and WIDTH, but here you get two different results. If we look at the logo from before, the result using STYLE="width:164px; height:150px" looks like this:

You browser does not suppert the HTML5 CANVAS tag.


while it looks like this, when using the attributes WIDTH="164" HEIGHT="150":

You browser does not suppert the HTML5 CANVAS tag.


So, if the image you get by using CANVAS is behaving strangely, it could be an inconsistency like this you are experiencing.


The difference between CANVAS and SVG

For graphics for websites, you have two options, SVG and CANVAS. We are looking at two different ways of working with graphics, with each their advantages and disadvantages. So, if you want to work with graphics, you should consider which type of graphics is the best for the project. The main differences are:

CANVASSVG
  • Dependent on resolution
  • Does not support event handlers
  • Poor rendering of text
  • The generated image can be saved as .png or .jpg
  • Well suited for graphic-intensive games
  • Independent of resolution
  • Supporting event handlers
  • Best suited for applications with large areas to be rendering (e.g. maps)
  • Slow rendering of complex images (anything using the DOM (Document Object Model) a lot will be slow)
  • Not suited for game applications



Properties and methods for CANVAS

If you should feel like doing some CANVAS coding, here is the names for some of the codes for properties and methods you can use:


Colors, Styles, and Shadows

PropertyDescription
fillStyleSyntax: context.fillStyle=color|gradient|pattern;
Specifies or returns the color, gradient, or pattern used to fill the drawing.
strokeStyleSyntax: context.strokeStyle=color|gradient|pattern;
Specifies or returns the color, gradient, or pattern used for strokes.
shadowColorSyntax: context.shadowColor=color;
Specifies or returns the color to use for shadows.
shadowBlurSyntax: context.shadowBlur=number;
Specifies or returns the blur level for shadows
shadowOffsetXSyntax: context.shadowOffsetX=number;
Specifies or returns the horizontal distance in pixels of the shadow from the shape.
shadowOffsetYSyntax: context.shadowOffsetY=number;
Specifies or returns the vertical distance in pixels of the shadow from the shape.


MethodDescription
createLinearGradient()Syntax: context.createLinearGradient=(x0,y0,x1,y1);
Creates a linear gradient (to use on canvas content). x0,y0,x1,y1 are the start and endpoints for the gradient, in pixels.
createPattern()Syntax: context.createPattern=(image,"repeat|repeat-x|repeat-y|no-repeat");
Repeats a specified element in the specified direction.
createRadialGradient()Syntax: context.createRadialGradient=(x0,y0,r0,x1,y1,r1);
Creates a radial/circular gradient (to use on canvas content).
addColorStop()Syntax: context.addColorStop=(stop,color);
Specifies the colors and stop positions in a gradient object. stop is a value between 0.0 and 1.0.


Line Styles

PropertyDescription
lineCapSyntax: context.lineCap=butt|round|square;
Specifies or returns the style of the end caps for a line.
lineJoinSyntax: context.lineJoin=bevel|round|miter;
Specifies or returns the type of corner created, when two lines meet.
lineWidthSyntax: context.lineWidth=number;
Specifies or returns the current line width in pixels.
miterLimitSyntax: context.miterLimit=number;
Specifies or returns the maximum miter length. Note that if the miter length exceeds the specified maximum miter length, the lineJoin will be displayed as "bevel".


Rectangles

MethodDescription
rect()Syntax: context.rect=(x,y,width,height);
Creates a rectangle. All values in pixels.
fillRect()Syntax: context.fillRect=(x,y,width,height);
Draws a "filled" rectangle. All values in pixels.
strokeRect()Syntax: context.strokeRect=(x,y,width,height);
Draws a rectangle (no fill). All values in pixels.
clearRect()Syntax: context.clearRect=(x,y,width,height);
Clears the specified pixels within a given rectangle, i.e. a white rectangle in the outer rectangle. All values in pixels.


Paths

MethodDescription
fill()Syntax: context.fill=();
Fills the current drawing (path) according to the specified parameters e.g. fillStyle().
stroke()Syntax: context.stroke=();
Actually draws the path you have defined, e.g. using lineTo() and moveTo(). beginPath=() starts the description and stroke=() ends the description.
beginPath()Syntax: context.beginPath=();
Begins a path, or resets the current path you have defined, e.g. using lineTo() and moveTo(). beginPath=() starts the description and stroke=() ends the description.
moveTo()Syntax: context.moveTo=(x,y);
Moves the path to the specified point in the canvas, without creating a line. Coordinates are i pixels.
closePath()Syntax: context.closePath=();
Creates a path from the current point back to the starting point.
lineTo()Syntax: context.lineTo=(x,y);
Adds a new point and creates a line to that point from the last specified point in the canvas.
clip()Syntax: context.clip=();
Clips a region of any shape and size from the original canvas.
quadraticCurveTo()Syntax: context.quadraticCurveTo=(cpx,cpy,x,y);
Creates a quadratic Bézier curve. Coordinates are i pixels.
bezierCurveTo()Syntax: context.bezierCurveTo=(cp1x,cp1y,cp2x,cp2y,x,y);
Creates a cubic Bézier curve. Coordinates are i pixels.
arc()Syntax: context.arc=(x,y,r,sAngle,eAngle,counterclockwise);
Creates an arc/curve (i.e. circles, or parts of circles).
arcTo()Syntax: context.arcTo=(x1,y1,x2,y2,r);
Creates an arc/curve between two tangents.
isPointInPath()Syntax: context.isPointInPath=(x,y);
Testing for whether the specified coordinate is on the specified path.


Transformations

MethodDescription
scale()Syntax: context.scale=(scalewidth,scaleheight);
Scales the current drawing bigger or smaller.
rotate()Syntax: context.rotate=(angle);
Rotates the current drawing.
translate()Syntax: context.translate=(x,y);
Remaps the (0,0) position on the canvas to the (x,y) coordinates. Coordinates in pixels.
transform()Syntax: context.transform=(a,b,c,d,e,f);
Replaces the current transformation matrix for the drawing.
setTransform()Syntax: context.setTransform=(a,b,c,d,e,f);
Resets the current transform to the identity matrix. Then runs transform().


Text

PropertyDescription
fontSyntax: context.font=font-style| font-variant| font-weight| font-size/line-height| font-family| caption| icon| menu| message-box| small-caption| status-bar;
Specifies or returns the current font properties for text content.
textAlignSyntax: context.textAlign=center|end|left|right|start;
Specifies or returns the current alignment for text content.
textBaselineSyntax: context.textBaseline=alphabetic|top|hanging|middle|ideographic|bottom;
Specifies or returns the current text baseline used when drawing text.


MethodDescription
fillText()Syntax: context.fillText=(text,x,y,maxWidth);
Draws "filled" text, i.e. not outlined text, on the canvas.
strokeText()Syntax: context.strokeText=(text,x,y,maxWidth);
Draws outlined text on the canvas.
measureText()Syntax: context.measureText=(text).width;
Returns an object that contains the width of the specified text.


Image Drawing

MethodDescription
drawImage()Syntax: context.drawImage=(img,sx,sy,swidth,sheight,x,y,width,height);
Draws an image, canvas, or video onto the canvas.


Pixel Manipulation

PropertyDescription
widthSyntax: imgData.width;
Returns the width of an ImageData object.
heightSyntax: imgData.height;
Returns the height of an ImageData object.
dataSyntax: imgData.data;
Returns an object that contains image data of a specified ImageData object.


MethodDescription
createImageData()Syntax: context.createImageData=(width,height) or context.createImageData=(imageData);
Creates a new, blank ImageData object.
getImageData()Syntax: context.getImageData=(x,y,width,height);
Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas.
putImageData()Syntax: context.putImageData=(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight);
Puts the image data (from a specified ImageData object) back onto the canvas.


Compositing
PropertyDescription
globalAlphaSyntax: context.globalAlpha=number;
Specifies or returns the current alpha or transparency value of the drawing. The transparency value must be a number between 0.0 (fully transparent) and 1.0 (no transparancy)
globalCompositeOperationSyntax: context.globalCompositeOperation=source-over| source-atop| source-in| source-out| destination-over| destination-atop| destination-in| destination-out| lighter| copy| xor;
Specifies or returns how a new image are drawn onto an existing image.


Other
MethodDescription
save()Syntax: context.save();
Saves the state of the current context.
restore()Syntax: context.restore();
Returns previously saved path state and attributes.
createEvent()Syntax: context.createEvent=(type);
Creates an event of the specified type. Please note that many methods used with createEvent, are deprecated. Use event constructors instead.
getContext()Syntax: context.getContext=(2d|webgl|webgl2|bitmaprenderer, contextAttributes);
Returns a drawing context on the canvas, or null if the context identifier is not supported.
toDataURL()Syntax: context.toDataURL=(type, encoderOptions);
Returns a data URI containing a representation of the image in the format specified by the type parameter (PNG is default). i.e. it converts the CANVAS image to .png or .jpg, depending on specification. The returned image is in a 96 dpi resolution.