我一直在尝试使用创建另一个画布的方法将图像裁剪为椭圆形,剪切,保存,然后将图像绘制到我的主画布上。但是,它只显示黑色椭圆形而没有覆盖在顶部的图像
var Ctx = document.getElementById('canvas').getContext('2d');
var tCan = document.createElement('canvas');
var tCtx = tCan.getContext('2d');
tCtx.beginPath();
var centerX = 50;
var centerY = 50;
var width = 100;
var height = 100;
tCtx.moveTo(centerX, centerY - height/2);
tCtx.bezierCurveTo(
centerX + width/2, centerY - height/2,
centerX + width/2, centerY + height/2,
centerX, centerY + height/2);
tCtx.bezierCurveTo(
centerX - width/2, centerY + height/2,
centerX - width/2, centerY - height/2,
centerX, centerY - height/2);
tCtx.fillStyle = "black";
tCtx.fill();
tCtx.closePath();
var img = new Image();
img.onload = function(){
tCtx.drawImage(img,1,1, 98, 98);
};
img.src = 'http://imgur.com/GvRewu7.png';
tCtx.clip();
var cSi = tCan.toDataURL();
var cImg = new Image();
cImg.src = cSi;
Ctx.drawImage(cImg,0,0);
为什么这不包括图像裁剪?有没有其他方法可以做到这一点(完全用javascript)?
编辑:我的活跃JSBin页面:https://jsbin.com/yulituc/edit?js,output
答案 0 :(得分:3)
jsFiddle:https://jsfiddle.net/mdofqjx2/3/
您尚未将新的canvas
元素添加到页面中。我已经为你修好了
HTML:
<canvas id="canvas" width="400" height="400">
</canvas>
<canvas id="canvas2" width="400" height="400">
</canvas>
Javascript:
var Ctx = document.getElementById('canvas').getContext('2d');
var tCan = document.getElementById('canvas2');
var tCtx = tCan.getContext('2d');
tCtx.beginPath();
var centerX = 50;
var centerY = 50;
var width = 100;
var height = 100;
tCtx.moveTo(centerX, centerY - height/2);
tCtx.bezierCurveTo(
centerX + width/2, centerY - height/2,
centerX + width/2, centerY + height/2,
centerX, centerY + height/2);
tCtx.bezierCurveTo(
centerX - width/2, centerY + height/2,
centerX - width/2, centerY - height/2,
centerX, centerY - height/2);
tCtx.fillStyle = "black";
tCtx.fill();
tCtx.closePath();
var img = new Image();
img.onload = function(){
tCtx.drawImage(img,1,1, 98, 98);
};
img.src = 'http://imgur.com/GvRewu7.png';
tCtx.clip();
var cSi = tCan.toDataURL();
jsFiddle:https://jsfiddle.net/mdofqjx2/1/
您可以创建路径然后绘制圆圈。如果要绘制椭圆,只需修改比例ctx.scale
var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
var img = new Image();
img.src = "https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg";
img.onload = function()
{
ctx.fillRect(0,0,c.width,c.height);
ctx.save();
ctx.scale(2,1);
ctx.beginPath();
ctx.arc(150, 150, 150, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.scale(0.5,1);
ctx.drawImage(img, 0, 0);
ctx.restore();
}