画布 - 剪辑多个图像
Canvas - clipping multiple images
我想将一堆图像剪辑成六边形。我让它工作了,但剪辑是跨所有十六进制的,而不是每个图像剪辑到只有一个十六进制。 我做错了什么?
这是一个现场演示:http://codepen.io/tev/pen/iJaHB
这是有问题的 js:
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise, img, imgX, imgY) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
// add stroke
ctx.lineWidth = 5;
ctx.strokeStyle = '#056e96';
ctx.stroke();
// add stroke
ctx.lineWidth = 4;
ctx.strokeStyle = '#47b6c8';
ctx.stroke();
// add stroke
ctx.lineWidth = 2;
ctx.strokeStyle = '#056e96';
ctx.stroke();
// Clip to the current path
ctx.clip();
ctx.drawImage(img, imgX, imgY);
ctx.restore();
}
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
var img2 = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
polygon(ctx, 120,120,100,6, 0,0,img, -120,-170);
}
img2.onload = function () {
polygon(ctx, 280,212,100,6, 0,0,img2, -150,-120);
}
// Specify the src to load the image
img.src = "http://farm8.staticflickr.com/7381/9601443923_051d985646_n.jpg";
img2.src = "http://farm6.staticflickr.com/5496/9585303170_d005d2aaa9_n.jpg";
您需要
将其添加到polygon()
方法中:
ctx.beginPath();
在此处查看修改后的笔
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise, img, ...
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.beginPath(); /// for example here, before moveTo/lineTo
ctx.moveTo(radius,0);
...
否则,线将累积,因此第二次调用多边形时,前一个多边形仍然存在。这就是为什么你也会在第一个六边形内看到部分图像的原因。
相关文章:
- 画布数据到图像
- 无法在本地计算机中将画布另存为图像
- HTML5在画布中加载较小的图像并保存实际大小的图像
- 如何将多个画布保存为一个图像
- 预览图像和画布
- 画布图像的问题
- 画布:逐像素绘制图像并请求动画帧计时
- 如何使图像在画布中移动
- 下载Div&画布为一个图像
- 用图像而不是颜色填充对象(将图像绘制到画布上)
- 绘制(重新加载)具有cors=“”的图像;匿名的“;在画布上(javascript)
- 如何用javascript下载画布图像(base64)
- 如何将图像画布数据发送到Transloadit
- Javascript CORS 图像/画布操作
- 使用fabric.js和HTML5在图像画布上编写自定义文本
- 图像画布HTML5
- 在不影响背景的情况下擦除图像画布上的线条
- IE10和跨域资源共享(CORS)问题与图像/画布
- 根据用户定义的角度旋转和图像画布
- 在HTML5图像画布中裁剪图像区域