コンテンツにスキップ

Canvasから画像を取り出して送信する

Canvasから画像を取り出して送信する

Canvasに描画した内容を画像として取り出し、OpenAI APIに送信する方法を学びます。

次のように index.html、style.css、main.js、そして画像ファイル(dog.png、bird.png、fish.png)を用意してください。

./works
└── get-image-from-canvas
├── index.html
├── style.css
├── main.js
└── assets
├── dog.png
├── bird.png
└── fish.png

ファイルの準備方法は以下のいずれかを選んでください:

  1. 画像をキャンバスに描く を終えたときのファイルをダウンロードする

    • 次のボタンからダウンロードし、解凍してできる put-image フォルダの名前を get-image-from-canvas に変えて、このセクションで必要な機能を追加していきます
    • 画像ファイルも assets フォルダに入っています
  2. 前の節で作成した自分のファイルを使用する

画像をキャンバスに描くを終えたときのファイル

前のステップまでの知識を組み合わせて、Canvasに描いた絵をOpenAI APIに送信し、評価を受け取る完全な機能を実装します。

用意したHTMLファイルに、評価ボタンと結果表示エリアを追加します。

変更点:

  • 「評価してもらう」ボタンを追加
  • 評価結果を表示するエリア(#result)を追加
index.html
6
6
<div>
7
7
<button id="clearButton">消す</button>
8
8
<input type="color" id="colorInput" value="#000000" />
9
<button id="evaluateButton">評価してもらう</button>
9
10
</div>
10
11
<div>
11
12
<img id="dogImage" src="./assets/dog.png" width="100" height="100" />
index.html
13
14
<img id="fishImage" src="./assets/fish.png" width="100" height="100" />
14
15
</div>
15
16
<canvas id="canvas" width="400" height="300"></canvas>
17
<div id="result">
18
<h2>評価結果</h2>
19
<p>スコア: <span id="score">-</span></p>
20
<p>コメント: <span id="comment">-</span></p>
21
</div>
16
22
<script src="./main.js"></script>
17
23
</body>
18
24
</html>

用意したJavaScriptファイルに、評価機能を追加します。

追加した機能:

  • OPENAI_API_KEY: APIキーの定数を追加
  • evaluateButton: 評価ボタンの要素を取得
  • scoreElement / commentElement: 評価結果を表示する要素を取得
  • Canvasから画像を取得: canvas.toDataURL('image/png') でBase64形式の画像データを取得
  • JSON構造を指定: response_format で score と comment を持つJSONを要求
  • 結果を表示: 受け取った score と comment を画面に表示
main.js
1
const OPENAI_API_KEY = 'YOUR_API_KEY_HERE';
2
1
3
const canvas = document.getElementById('canvas');
2
4
const clearButton = document.getElementById('clearButton');
3
5
const colorInput = document.getElementById('colorInput');
4
6
const dogImage = document.getElementById('dogImage');
5
7
const birdImage = document.getElementById('birdImage');
6
8
const fishImage = document.getElementById('fishImage');
9
const evaluateButton = document.getElementById('evaluateButton');
10
const scoreElement = document.getElementById('score');
11
const commentElement = document.getElementById('comment');
7
12
8
13
let drawing = false;
main.js
53
58
const ctx = canvas.getContext('2d');
54
59
ctx.drawImage(fishImage, 0, 0, 400, 300);
55
60
});
61
62
evaluateButton.addEventListener('click', async () => {
63
console.log('評価ボタンがクリックされました');
64
65
const imageDataUrl = canvas.toDataURL('image/png');
66
67
const response = await fetch('https://api.openai.com/v1/chat/completions', {
68
method: 'POST',
69
headers: {
70
'Content-Type': 'application/json',
71
'Authorization': `Bearer ${OPENAI_API_KEY}`
72
},
73
body: JSON.stringify({
74
model: 'gpt-6-luna',
75
messages: [
76
{
77
role: 'user',
78
content: [
79
{
80
type: 'text',
81
text: 'この絵を評価してください'
82
},
83
{
84
type: 'image_url',
85
image_url: {
86
url: imageDataUrl
87
}
88
}
89
]
90
}
91
],
92
response_format: {
93
type: 'json_schema',
94
json_schema: {
95
name: 'image_evaluation',
96
strict: true,
97
schema: {
98
type: 'object',
99
properties: {
100
score: {
101
type: 'number',
102
description: '絵の評価スコア (0-100)'
103
},
104
comment: {
105
type: 'string',
106
description: '評価コメント'
107
}
108
},
109
required: ['score', 'comment'],
110
additionalProperties: false
111
}
112
}
113
}
114
})
115
});
116
117
const data = await response.json();
118
console.log('レスポンス:', data);
119
120
const result = JSON.parse(data.choices[0].message.content);
121
console.log('評価スコア:', result.score);
122
console.log('コメント:', result.comment);
123
124
scoreElement.textContent = result.score;
125
commentElement.textContent = result.comment;
126
});
const imageDataUrl = canvas.toDataURL('image/png');

canvas.toDataURL('image/png') メソッドを使うと、Canvasの内容をBase64エンコードされたPNG画像として取得できます。これをそのままOpenAI APIの image_url.url に渡すことができます。

response_format: {
type: 'json_schema',
json_schema: {
name: 'image_evaluation',
strict: true,
schema: {
type: 'object',
properties: {
score: {
type: 'number',
description: '絵の評価スコア (0-100)'
},
comment: {
type: 'string',
description: '評価コメント'
}
},
required: ['score', 'comment'],
additionalProperties: false
}
}
}

OpenAI APIの Structured Outputs 機能を使って、レスポンスのJSON構造を指定します。これにより、必ず score(数値)と comment(文字列)を含むJSONが返されます。

scoreElement.textContent = result.score;
commentElement.textContent = result.comment;

APIから返された評価結果を画面に表示します。

  1. OPENAI_API_KEYを実際のAPIキーに置き換える
  2. ブラウザでHTMLファイルを開く
  3. Canvasに絵を描くか、サンプル画像をクリックして配置
  4. 「評価してもらう」ボタンをクリック
  5. 評価結果(スコアとコメント)が画面に表示されることを確認

この節のプレビューは API キーが必要なので、サイト上には置いていません。

このセクションで学んだ内容を統合することで、ブラウザベースのお絵描き評価アプリケーションを作成できます。

  • canvas.toDataURL() でCanvasの内容をBase64画像として取得
  • OpenAI APIにBase64画像を送信
  • Structured Outputsで構造化されたJSON(score/comment)を取得
  • 画面に評価結果を表示

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
この節を終えたときのファイル