Canvas
// function to display mouse position relative to canvas
function getRelativeMousePosition(canvas, event) {
return {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
}
// create data object for image: ImageData { width: px, height: px, data: Uint8ClampedArray }
var imageData = context.createImageData(width, height); // width and height of image
OR
.createImageData(imagedata); // copy dimensions (not the image data) of another object
imageData = context.getImageData(startX, startY, width, height); // get contents of canvas within given dimensions
putImageData(context, imageData, X, // where to place the image on the canvas
Y, // where to place the image on the canvas
dirtyX, // first horizontal pixel of image data to display (if not 0, image shifts towards right)
dirtyY, // first vertical pixel of image data to display (if not 0, image shifts towards bottom)
width, // width drawn
height); // height drawn
var externalImage = new Image();
externalImage.onload = function () {
context.drawImage(externalImage, 0, 0);
};
externalImage.src = "http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png";
// this must be called from within an onload function to make sure it's been loaded
var imageObj = document.getElementsByTagName('img')[0];
context.drawImage(imageObj, 10, 10, 30, 30);
// drawImage can get a video element and draw its currently played frame
function drawSomething() {
// save global context
context.save();
// change local context and execute drawing
// restore global context for further work outside this function
context.restore();
}
// define colour (any CSS3 colour string can be used)
context.strokeStyle OR context.fillStyle = colour;
// draw a rectangle
context.strokeRect OR context.fillRect(x, y, width, height);
// delete a filled rectangle
context.clearRect(x, y, width, height);
// delete a stroke rectangle
context.clearRect(x - 1, y - 1, width + 2, height + 2);
// define direction of gradient
gradientName = context.createLinearGradient(startX , startY, endX, endY);
OR
gradientName = context.createRadialGradient(innerX, innerY, innerRadius, outerX, outerY, outerRadius);
// set starting colour
gradientName.addColorStop(0, colour);
// set a different colour with its peek point somewhere between 0 and 1
gradientName.addColorStop(0.3153, anotherColour);
// set ending colour
gradientName.addColorStop(1, differentColour);
// set working colour to the gradient created above
context.strokeStyle OR context.fillStyle = gradientName;
// finally draw something to actually make use of the gradient
// define font ([font style][font weight][font size][font face])
context.font = 'italic 20pt Calibri';
// define text position
context.textBaseline = 'top|hanging|middle|alphabetic|ideographic|bottom';
context.textAlign = 'center|start|end|left|right';
// write text
context.strokeText OR context.fillText(string, x, y[, maxWidth]);
// reset bufer but leave context properties as they are
context.beginPath();
context.moveTo(x, y);
context.lineTo(x, y);
// draw arc - drawInverse: optional (default: false), draws complementary arc if true
context.arc(cx, cy, radius, startAngle, endAngle, drawInverse);
// draw arc from current position through corner to endpoint
context.arcTo(cornerX, cornerY, endX, endY, radius);
// quadratic Bézier curve
context.quadraticCurveTo(controlX, controlY, endX, endY);
// cubic Bézier curve
context.bezierCurveTo(firstControlX, firstControlY, secondControlX, secondControlY, endX, endY);
// curve code automat: http://www.victoriakirst.com/beziertool/
// arrows: http://www.dbp-consulting.com/tutorials/canvas/CanvasArrow.html
// draw a line from last point to first
context.closePath();
context.rect(x, y, width, height);
// execute drawing
context.stroke(); OR context.fill();
// resizing by JavaScript erases the canvas
<script>
function resizeCanvas(width, height) {
canvas.width = width;
canvas.height = height;
}
</script>
// resizing by CSS scales the canvas to its new dimensions
<style>
#myCanvas {
border: 1px solid black;
width:100%
}
</style>
// proper method: resize & redraw
<style>
#parentDiv {
width:100%;
height:100%;
canvas {
border: 1px solid black;
}
}
</style>
<script>
function resizeCanvasAccordingToParentSize() {
// adjust canvas size, take parent's size, this erases content
canvas.width = parentDiv.clientWidth;
canvas.height = parentDiv.clientHeight;
// draw something, taking into account the new canvas size
...
}
</script>
var loopReference;
function animationLoop(timeStamp) {
// 1 - Clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2 Draw
someDrawFunction();
// 3 Move
figurePosition++;
// call mainloop again after 16.6ms (corresponds to 60 frames/second)
loopReference = requestAnimationFrame(animationLoop);
}
loopReference = requestAnimationFrame(animationLoop);
var init = function() {
canvas = document.getElementsByTagName('canvas')[0];
context = canvas.getContext('2d');
// the canvas can be turned into data url, default type is image/png, encoder options is a number between 0 and 1 representing image quality
var savedCanvas = canvas.toDataURL(type, encoderOptions);
// scale context
context.scale(x, y);
// rotate context
context.rotate(Math.PI / 2);
// shift context
context.translate(x, y);
// define line width and end style
context.lineWidth = 3;
context.lineCap = 'butt|square|round';
context.lineJoin = 'miter|bevel|round';
// forces miter to change to bevel if angle is too sharp (e.g. 1, 2, 3, ...)
context.ctx.miterLimit = limit;
// define shadow
context.shadowColor = colour; // colour to use for shadows,
context.shadowBlur = blurInPx; // blur level for shadows,
context.shadowOffsetX = offsetX; // horizontal distance of the shadow from the shape,
context.shadowOffsetY = offsetY; // vertical distance of the shadow from the shape
};