图像上的圆角

Emi*_*ray 4 javascript css html5 canvas

假设我通过在HTML5画布中创建一个形状然后用图像填充它来创建一个多边形图像,例如如下所示:

在此输入图像描述

现在我想围绕这个六边形的角落.

有一个lineJoin = "round"属性可用,但这似乎不起作用(我相信因为形状已填充,没有外线可以圆).

有没有人知道如何使用HTML5画布或任何其他方式?

以下是用于创建图像的代码:

var ctx = document.getElementById('myCanvas').getContext('2d');
var a = ctx.canvas.width, r = a / 5;

var side = Math.sqrt((4/3) * r * r);


// Draw your image onto the canvas (here I'll just fill the
// surface with red
var img = new Image();
img.src = "https://upload.wikimedia.org/wikipedia/commons/0/03/Mountain_Bluebird.jpg";

img.onload = function () {
    var pattern = ctx.createPattern(img, "no-repeat");
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, a, a);
  
  // Switch the blending mode
  ctx.globalCompositeOperation = 'destination-in';

  // Draw the hexagon shape to mask the image
  ctx.beginPath();
  ctx.moveTo(0, side/2);
  ctx.lineTo(0, 3*side/2);
  ctx.lineTo(r, 2*side);
  ctx.lineTo(2*r, 3*side/2);
  ctx.lineTo(2*r, side/2);
  ctx.lineTo(r, 0);
  ctx.closePath();
  ctx.fill();
};
Run Code Online (Sandbox Code Playgroud)
<canvas width="1000" height="1000" id="myCanvas"></canvas>
Run Code Online (Sandbox Code Playgroud)

pot*_*ngs 5

只需更改您绘制的顺序,然后更改globalCompositeOperation'source-in'.

我做了一些调整,因为你的代码中的一些角被剪掉但没有调整图像位置(我希望这很容易做到)


预习

您需要像我说的那样调整图像位置

在此输入图像描述


片段

var ctx = document.getElementById('myCanvas').getContext('2d');
var a = ctx.canvas.width, r = a / 5;

var side = Math.sqrt((4/3) * r * r) - 20;


// Draw your image onto the canvas (here I'll just fill the
// surface with red
var img = new Image();
img.src = "https://upload.wikimedia.org/wikipedia/commons/0/03/Mountain_Bluebird.jpg";

img.onload = function () {
  
  ctx.lineJoin = "round";
  ctx.lineWidth = 50;

  // Draw the hexagon shape to mask the image
  ctx.beginPath();
  ctx.moveTo(50, 50 + side/2);
  ctx.lineTo(50, 50 + 3*side/2);
  ctx.lineTo(50 + r, 50 + 2*side);
  ctx.lineTo(50 + 2*r, 50 + 3*side/2);
  ctx.lineTo(50 + 2*r, 50 + side/2);
  ctx.lineTo(50 + r, 50);
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
  
  // Switch the blending mode
  ctx.globalCompositeOperation = 'source-in';
  var pattern = ctx.createPattern(img, "no-repeat");
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, a, a);
  
};
Run Code Online (Sandbox Code Playgroud)
<canvas width="1000" height="1000" id="myCanvas"></canvas>
Run Code Online (Sandbox Code Playgroud)