javascript - Canvas - 裁剪多个图像

标签 javascript html canvas

我想将一堆图像剪辑成六边形。 我让它有点工作,但剪裁是跨越所有六 Angular 形,而不是每个图像只剪裁到一个六 Angular 形。我做错了什么?

这是一个现场演示: 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();

参见 modified pen here

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

否则,线条会堆积起来,因此您第二次调用多边形时,之前的多边形仍然存在。这就是为什么您在第一个六边形内也看到了部分图像。

关于javascript - Canvas - 裁剪多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012168/

相关文章:

javascript - 如何向 chart.js 折线图添加点?

javascript - 在组件安装上 react 查询数据库?

javascript - 如何在悬停时在右侧显示弹出窗口?

javascript - 如何将粒子系统初始化为球冠?

javascript - Shiny 的 HTML UI 受 Javascript OnLoad 限制?

javascript - 如何使具有多个绝对定位元素的 div 响应

image - 将多个图像保存为视频格式的可能性?

javascript - 将 HTML5 Canvas (视频)元素分割成多个部分

javascript - 修复面包屑的响应性

php - 动态生成的表单无法正常工作