I just wanted to clip image in a curve .. but not happening this.. Only image is showing and but not with clip.
JavaScript
x
48
48
1
var canvas = document.getElementById('leaf');
2
var context = canvas.getContext('2d');
3
4
/*
5
* save() allows us to save the canvas context before
6
* defining the clipping region so that we can return
7
* to the default state later on
8
*/
9
10
context.save();
11
context.beginPath();
12
context.moveTo(188, 150);
13
context.quadraticCurveTo(288, 0, 388, 150);
14
context.lineWidth = 10;
15
context.quadraticCurveTo(288, 288, 188, 150);
16
context.lineWidth = 10;
17
18
context.clip();
19
20
context.beginPath();
21
var imageObj = new Image();
22
imageObj.onload = function() {
23
context.drawImage(imageObj, 10, 50);
24
};
25
26
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
27
28
/* context.beginPath();
29
context.arc(x - offset, y - offset, radius, 0, 2 * Math.PI, false);
30
context.fillStyle = 'yello';
31
context.fill();
32
*/
33
34
/*
35
* restore() restores the canvas context to its original state
36
* before we defined the clipping region
37
*/
38
39
context.restore();
40
context.beginPath();
41
context.moveTo(188, 150);
42
context.quadraticCurveTo(288, 0, 388, 150);
43
context.lineWidth = 10;
44
context.quadraticCurveTo(288, 288, 188, 150);
45
context.lineWidth = 10;
46
47
context.strokeStyle = 'blue';
48
context.stroke();
JavaScript
1
2
1
<canvas id="leaf" width="500" height="500" style='left: 0;
2
position: absolute; top: 0;'></canvas>
Advertisement
Answer
You have to move everything from the line context.save();
to context.clip();
inside the function object of your imgObj
‘s onload
handler:
JavaScript
1
13
13
1
imageObj.onload = function()
2
{
3
context.save();
4
context.beginPath();
5
context.moveTo(188, 150);
6
context.quadraticCurveTo(288, 0, 388, 150);
7
context.lineWidth = 10;
8
context.quadraticCurveTo(288, 288, 188, 150);
9
context.lineWidth = 10;
10
context.clip();
11
context.drawImage(imageObj, 10, 50);
12
};
13
See http://jsfiddle.net/CSkP6/1/ for an example.