Help us understand the problem. What is going on with this article?

canvasで処理した画像をThree.jsのテクスチャとして描画する.

More than 3 years have passed since last update.

やりたいこと

canvasで画像をclip処理してから,Three.jsで3D空間上に描画したい.

やり方

clip処理はcanvasのclipメソッドで要素を切り取る.

Three.jsのテクスチャでは,img要素,canvas要素,video要素など幅広い要素をマッピングさせることができるの,それを利用する.

書いてみたコード

// canvasを定義する
var imagecanvas = document.createElement('canvas'),
    imagecontext = imagecanvas.getContext('2d');

imagecanvas.width = 350;
imagecanvas.height = 350;

// クリップする円の位置と半径を指定する
imagecontext.beginPath();
imagecontext.arc(175, 175, 175, 0, Math.PI*2, false);
imagecontext.clip();

// 画像を用意する
var img4 = new Image();
img4.src = "image/***.jpg";
img4.onload = function(){
  imagecontext.drawImage(img4, 160, 0, 350, 350, 0, 0, 350, 350);

  // Textureとして指定する.以下Three.jsでよくあるオブジェクト描画と同じ
  var imagetexture = new THREE.Texture(imagecanvas);
  imagetexture.needsUpdate = true; 
  var imagematerial = new THREE.SpriteMaterial( { map: imagetexture, color: 0xffffff } );
  var imagesprite = new THREE.Sprite( imagematerial );
  imagesprite.scale.set(200, 200, 200);
  imagesprite.position.set(0, 0, 0);

  scene.add( imagesprite );
}

画像は読み込んでからでないと描画できないので,onloadで描画しています.

こうすると,onloadメソッドは非同期なのでfor文でループしている時は処理がうまくいかず大変ですが,そんな時は,
image onloadをfor文で回す際の注意-Qiita
これのコメント欄を参考にするといいと思います.

参考ページ

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away