Để cắt một vùng được sử dụng trong HTML5 Canvas, chúng ta có thể vẽ vùng đó và dùng phương thức clip(). Hay nói cách khác, dùng phương thức clip để xóa đi những vùng bên ngoài nó.

Cú pháp:

1
context.clip();

Javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;
    var radius = 75;   
    var offset = 50;
 
    // define circle clipping region
    // save() allows us to save the canvas context before
    // defining the clipping region so that we can return
    // to the default state later on
    context.save();
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.clip();
 
    // draw blue circle inside clipping region
    context.beginPath();
    context.arc(centerX - offset, centerY - offset, radius, 0, 2 * Math.PI, false);
    context.fillStyle = "#00D2FF"; // light blue
    context.fill();
 
    // draw yellow circle inside clipping region
    context.beginPath();
    context.arc(centerX + offset, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = "yellow";
    context.fill();
 
    // draw red circle inside clipping region
    context.beginPath();
    context.arc(centerX, centerY + offset, radius, 0, 2 * Math.PI, false);
    context.fillStyle = "red";
    context.fill();
 
    // restore() restores the canvas context to its original state
    // before we defined the clipping region
    context.restore();
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.lineWidth = 3;
    context.strokeColor = "black";
    context.stroke();
};
 
Nếu bạn vẫn chưa hiểu chức năng của nó thì bạn có thể xóa bỏ dòng gọi phương thức clip có thể bạn sẽ hểu hơn. Thử dùng phương thứ này với những đường vẽ khác hình tròn xem sao nhé.