0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

canvasを使って、Imageオブジェクトにアウトラインを引く方法

Posted at

目標

透過色付きpngを読み込んで、その画像の縁に沿ってラインを引きます。
今回の方法はブラウザでもnode上で動くnode-canvasでも使える方法です。
image.png

コード

一例として、読み込んだImageの縁に黒いラインをつける。

  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')

  // Imageオブジェクトを読み込む。今回はネット上の画像を使う。
  // node-canvasの場合`const img = await loadImage(imagePath)`とかで可能
  const img = new Image;
  img.onload = draw;
  img.src = "http://i.stack.imgur.com/UFBxY.png";

  const s = 10; // thickness scale
  const x = 0; // final position
  const y = 0;

function draw() {
  for (let i = 0; i < 360; i++)
    ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);

  ctx.globalCompositeOperation = 'source-in';
  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 合成モードを'source-over'に戻して上書き
  ctx.globalCompositeOperation = 'source-over';
  ctx.drawImage(img, 0,0,img.width, img.height);
}
 
 

参考

Draw outline from image

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?