Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas clip image in a circle

I just wanted to clip image in a curve .. but not happening this.. Only image is showing and but not with clip.

var canvas = document.getElementById('leaf');
var context = canvas.getContext('2d');

/*
 * 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.moveTo(188, 150);
context.quadraticCurveTo(288, 0, 388, 150);
context.lineWidth = 10;
context.quadraticCurveTo(288, 288, 188, 150);
context.lineWidth = 10;

context.clip();

context.beginPath();
var imageObj = new Image();
imageObj.onload = function() {
  context.drawImage(imageObj, 10, 50);
};

imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

/* context.beginPath();
context.arc(x - offset, y - offset, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'yello';
context.fill();
*/

/*
 * restore() restores the canvas context to its original state
 * before we defined the clipping region
 */

context.restore();
context.beginPath();
context.moveTo(188, 150);
context.quadraticCurveTo(288, 0, 388, 150);
context.lineWidth = 10;
context.quadraticCurveTo(288, 288, 188, 150);
context.lineWidth = 10;

context.strokeStyle = 'blue';
context.stroke();
<canvas id="leaf" width="500" height="500" style='left: 0; 
    position: absolute; top: 0;'></canvas>
like image 418
Naresh Avatar asked Mar 22 '13 08:03

Naresh


2 Answers

You have to move everything from the line context.save(); to context.clip(); inside the function object of your imgObj's onload handler:

imageObj.onload = function()
{
    context.save();
    context.beginPath();
    context.moveTo(188, 150);
    context.quadraticCurveTo(288, 0, 388, 150);
    context.lineWidth = 10;
    context.quadraticCurveTo(288, 288, 188, 150);
    context.lineWidth = 10;
    context.clip();
    context.drawImage(imageObj, 10, 50);
};

See http://jsfiddle.net/CSkP6/1/ for an example.

like image 165
halex Avatar answered Nov 20 '22 10:11

halex


When, a few time after your script is launched, your image gets loaded, you have no more a clipped Canvas since you restore it afterwise.
You need to do a drawClipped function, and call it in your onload function for instance :

function drawClipped(context, myImage) = {
   context.save();
   context.beginPath();
   context.moveTo(188, 150);
   context.quadraticCurveTo(288, 0, 388, 150);
   context.lineWidth = 10;
   context.quadraticCurveTo(288, 288, 188, 150);
   context.lineWidth = 10;
   context.clip();
   context.drawImage(myImage, 10, 50);
   context.restore();
};

var imageObj = new Image();
imageObj.onload = function()  {
    drawClipped(context, imageObj);
};

imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
like image 2
GameAlchemist Avatar answered Nov 20 '22 09:11

GameAlchemist