我有一些代码将一堆图像加载到隐藏的img元素中,然后是一个Javascript循环,将每个图像放到画布上.但是,我想剪切每个图像,使其在放置在画布上时为圆形.
我的循环看起来像这样:
$$('#avatars img').each(function(avatar) {
var canvas = $('canvas');
var context = canvas.getContext('2d');
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.beginPath();
context.arc(x+24, y+24, 20, 0, Math.PI * 2, 1);
context.clip();
context.strokeStyle = "black";
context.drawImage(document.getElementById(avatar.id), x, y);
context.stroke();
});
Run Code Online (Sandbox Code Playgroud)
问题是,只绘制(或可见)第一个图像.
如果我删除剪切逻辑:
$$('#avatars img').each(function(avatar) {
var canvas = $('canvas');
var context = canvas.getContext('2d');
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.drawImage(document.getElementById(avatar.id), x, y);
});
Run Code Online (Sandbox Code Playgroud)
然后绘制我的所有图像.
有没有办法让每张图片分别剪裁?
我尝试将剪切区域重置为图像之间的整个画布,但这不起作用.