ラベル canvas の投稿を表示しています。 すべての投稿を表示
ラベル canvas の投稿を表示しています。 すべての投稿を表示

2013年5月12日日曜日

Cutting out rounded rectangle from canvas in JavaScript

In JavaScript, you can easily cut out rounded rectangle from existing canvas drawings, using the combination of the two technics; drawing a rounded rectangle and globalCompositionOperation = 'destination-in'.

First, you draw anything you want on any position of the canvas, then set the canvas context's globalCompositionOperation property to 'destination-in' and then fill rounded rectangle using above technic and you get rounded version of your image :)

The following function cut out rounded rectangle with given left, top, width and height and rounding radius on given canvas context.

var cutRoundedRect = function(ctx, radius, x, y, w, h) {
    var left = x;
    var top = y;
    var right = x + w;
    var bottom = y + h;

    ctx.globalCompositeOperation = 'destination-in';
    ctx.fillStyle = 'black';

    ctx.beginPath();
    ctx.moveTo(left + radius, top);
    ctx.lineTo(right - radius, top);
    ctx.quadraticCurveTo(right, top, right, top + radius);
    ctx.lineTo(right, bottom - radius);
    ctx.quadraticCurveTo(right, bottom, right - radius, bottom);
    ctx.lineTo(left + radius, bottom);
    ctx.quadraticCurveTo(left, bottom, left, bottom - radius);
    ctx.lineTo(left, top + radius);
    ctx.quadraticCurveTo(left, top, left + radius, top);
    ctx.fill();
};