Masking an image to the canvas
HTML
<canvas id="tutorial" width="200" height="158"></canvas>
CSS
body {
background: #CEF;
}
JavaScript
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.beginPath();
roundRect(ctx,0,0,50,40,10,0,1)
ctx.clip();
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
}
img.src = 'http://javascript.ru/cat/list/donkey.gif';
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}