簡體   English   中英

畫布剪輯圖像在一個圓圈

[英]canvas clip image in a circle

我只是想在曲線中剪輯圖像..但是沒有發生這種情況..只有圖像顯示,但不是剪輯。

HTML

<canvas id="leaf" width="500" height="500" style='left: 0; 
position: absolute; top: 0;'></canvas>

JavaScript的

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();

你必須從行context.save(); to context.clip(); imgObjonload處理程序的函數對象中:

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);
};

有關示例,請參見http://jsfiddle.net/CSkP6/1/

在腳本啟動幾次之后,當您的圖像被加載時,您不再需要剪切的畫布,因為您之后會恢復它。
你需要做一個drawClipped函數,並在你的onload函數中調用它,例如:

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';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM