LoginSignup
0
0

More than 3 years have passed since last update.

【入門者向け】Canvas入門講座#1 塗りつぶそう【JavaScript】

Last updated at Posted at 2020-11-10

問題1

赤色でcanvasを塗りつぶしなさい。
なお、以下のHTMLを使うこと。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>問題1</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(() => {
    // ここにプログラムを書く
});
</script>
</head>
<body>
<canvas id="my-canvas" width="500" height="300"></canvas>
</body>
</html>

答え

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>問題1</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(() => {
    const ctx = $('#my-canvas')[0].getContext('2d');
    ctx.fillStyle = '#ff0000';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});
</script>
</head>
<body>
<canvas id="my-canvas" width="500" height="300"></canvas>
</body>
</html>

こんな感じで塗りつぶせると思います。
ダウンロード (3).png

解説

まずはコンテキストを取得しましょう。
このコンテキストを使ってcanvasに描画します。

const ctx = $('#my-canvas')[0].getContext('2d');

次に色を赤色で指定します。

ctx.fillStyle = '#ff0000';

最後に塗りつぶします。
このfillRectというメソッドは頻繁に使うので覚えておきましょう。
ctx.canvasのようにコンテキストのプロパティに
コンテキストを取得したcanvasがあるので、これも知っておくとよいでしょう。

ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
0
0
2

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
0