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.

始点と終点をクリックして画像を黒塗りにする方法

Last updated at Posted at 2020-08-05

http://pic2change.qcweb.jp/
というサイトをデプロイしたのですが閉めてしまうので記念に記事を書いておきます。
仕組みは簡単。画像をJSで読み込み矩形の目隠しをする、サイトです。
どうせJSなのでコードを見ようとすれば見えるので共有しておきます。

スクリーンショット 2020-08-05 16.29.21.png
document.getElementById('file').addEventListener('change', function (e){
var file = e.target.files[0];
// ファイルのブラウザ上でのURLを取得する
var blobUrl = window.URL.createObjectURL(file);
var img = new Image();
var flg = true;
var flg2 = false;
var first_x = null;
var first_y = null;
var last_x = null;
var last_y = null;
var base1 = null;
var data = null;
img.src = blobUrl;
var w =null;
var h = null;

var canvas = document.getElementById('screen_image');
if (canvas && canvas.getContext) {
  var ctx = canvas.getContext('2d');
  img.onload = function () {
    w = img.width;
    h = img.height;
    canvas.width = w;
    canvas.height = h;
    ctx.drawImage(img, 0, 0);
    canvas.addEventListener("click", first_click, false);
    canvas.addEventListener("click", fill_rect, false);

  };
//始点と終点の情報を取得、メソッドを分割しても良かった気がする
  var first_click = function (e) {
    var rect = e.target.getBoundingClientRect();
    if (flg) {
      first_x = e.clientX - rect.left;
      first_y = e.clientY - rect.top;
      flg = false;
    } else {
      last_x = e.clientX - rect.left;
      last_y = e.clientY - rect.top;
      flg = true;
      flg2 = true;
    }
  };
  document.getElementById("btn1").addEventListener("click", function(){
    var link = document.getElementById('download');
    link.href = canvas.toDataURL();
    link.download = 'download.png';
    link.click();
  });
//黒塗りする
  var fill_rect = function () {
    if (flg2 === true) {
      if (first_x > last_x) {
        [first_x, last_x] = [last_x, first_x];
      }
      if (first_y > last_y) {
        [first_y, last_y] = [last_y, first_y];
      }
      ctx.fillStyle = "rgb(0, 0, 0)";
      ctx.fillRect(first_x, first_y, last_x - first_x, last_y - first_y);
      flg2 = false;
      data = canvas.toDataURL('image/png');
      document.getElementById('screen_image').value = data;
    }
  };
}
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?