canvas-border-experiment

by Richard Hunter

HTML

<canvas id="tutorial"></canvas>
<div class="box"></div>

CSS

canvas {
  width: 100px;
  height: 100px;
  background: pink;
  transform: scale(1);
}

.box {
  background: green;
  width: 100px;
  height: 100px;
  display: inline-block;
}

JavaScript

function download(blobUrl, name) {
  var link = document.createElement("a");
  link.download = name;
  link.style.opacity = "0";
  document.body.append(link);
  link.href = blobUrl;
  link.click();
  link.remove();
}


const multiplier = 20;
const canvas = document.getElementById("tutorial");
canvas.width = 100 * multiplier;
canvas.height = 100 * multiplier;
const ctx = canvas.getContext("2d");

ctx.fillStyle = "blue";
const rectWidth = 50 * multiplier;
const rectHeight = 50 * multiplier;
const borderWidth = 10 * multiplier;
ctx.fillRect(10 * multiplier, 10 * multiplier, rectWidth, rectHeight);

drawBorders(10 * multiplier, 10 * multiplier, rectWidth, rectHeight, [borderWidth, borderWidth, borderWidth, borderWidth], ['hotpink', 'hotpink', 'hotpink', 'hotpink']);

const blobUrl = canvas.toDataURL();
download(blobUrl, 'test.png');

function drawBorders(x, y, width, height, borderWidths, borderColors) {
  // top border

  ctx.fillStyle = borderColors[0];
  ctx.beginPath()
  ctx.moveTo(x, y);
  ctx.lineTo(x + width, y);
  ctx.lineTo(x + width - borderWidths[1], y + borderWidths[0]);
  ctx.lineTo(x + borderWidths[3], y + borderWidths[0]);
  ctx.closePath();
  ctx.fill();
  // right border
  ctx.fillStyle = borderColors[1];
  ctx.beginPath()
  ctx.moveTo(x + width, y);
  ctx.lineTo(x + width, y + height);
  ctx.lineTo(x + width - borderWidths[1], y + height - borderWidths[2]);
  ctx.lineTo(x + width - borderWidths[1], y + borderWidths[0]);
  ctx.closePath();
  ctx.fill();
  //bottom border
  ctx.fillStyle = borderColors[2];
  ctx.beginPath()
  ctx.moveTo(x + width, y + height);
  ctx.lineTo(x, y + height);
  ctx.lineTo(x + borderWidths[3], y + height - borderWidths[2]);
  ctx.lineTo(x + width - borderWidths[1], y + height - borderWidths[2]);
  ctx.closePath();
  ctx.fill();

  ctx.fillStyle = borderColors[3];
  ctx.beginPath()
  ctx.moveTo(x, y);
  ctx.lineTo(x, y + height);
  ctx.lineTo(x + borderWidths[3], y + height - borderWidths[2]);
  ctx.lineTo(x +...