我正在尝试从2张图片中裁剪出一个圆圈并将它们并排放置:
const ctx = $('#canvas')[0].getContext("2d");
const image = new Image();
image.onload = () => {
const coords = [[115, 62.5], [495, 62.5]];
const coords2 = [[65, 12.5] , [445, 12.5]];
for(let i = 0; i < coords.length; i++) {
ctx.beginPath();
ctx.arc(coords[i][0], coords[i][1], 50, 0, Math.PI * 2, true);
ctx.clip();
ctx.drawImage(image, coords2[i][0], coords2[i][1], 100, 100);
}
};
image.src = 'https://placeholdit.imgix.net/~text?txtsize=50&w=700&h=250&bg=afeafe';
&#13;
#canvas {
border:1px solid grey;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>
&#13;
然而,这只是裁剪其中一张图片而另一张没有显示,我不明白为什么?
当我注释掉这些行
时ctx.beginPath();
ctx.arc(coords[i][0], coords[i][1], 50, 0, Math.PI * 2, true);
ctx.clip();
正确放置2张图像,因此定位不是问题。
答案 0 :(得分:0)
通过在裁剪之前保存上下文然后在裁剪之后恢复它来修复:
const ctx = $('#canvas')[0].getContext("2d");
const image = new Image();
image.onload = () => {
const coords = [[115, 62.5], [495, 62.5]];
const coords2 = [[65, 12.5] , [445, 12.5]]
for(let i = 0; i < coords.length; i++) {
ctx.save();
ctx.beginPath();
ctx.arc(coords[i][0], coords[i][1], 50, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.drawImage(image, coords2[i][0], coords2[i][1], 100, 100);
ctx.restore();
}
};
image.src = 'https://placeholdit.imgix.net/~text?txtsize=50&w=700&h=250&bg=afeafe';
#canvas {
border:1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>