0
0

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 1 year has passed since last update.

canvasを使ってみる

Posted at

この記事の目的

canvasの基本的な使い方をマスターする。

canvasとは

canvasとは、HTML5から使えるようになった、グラフィックやアニメーションを描画することができる機能です。

使い方

1. HTMLのbody要素内にcanvas要素を用意する

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <!-- 中略 -->
        <script src="canvas.js" defer></script>
    </head>
    <body>
        <canvas id="my-canvas" width="1000" height="800">
            ここに代替コンテンツを記述します
        </canvas>
    </body>
</html>

代替コンテンツとは
canvasに対応していない古いブラウザやJavaScriptが無効なブラウザで、canvasの代わりに表示されるコンテンツのことです。canvasが問題なく表示できる場合は代替コンテンツは無視されます。

2. 描画コンテキストを取得する

JavaScript コード内で HTMLCanvasElement.getContext() を呼び出して描画コンテキストを取得し、キャンバス上に描画を開始します。

canvas.js
const myCanvas = document.querySelector('#my-canvas');
const ctx = myCanvas.getContext('2d');   // 描画Contextを取得
ctx.fillStyle = "green";                // 塗りつぶしの色を設定
ctx.fillRect(10, 10, 100, 100);         // 座標(10, 10)に横100px縦100pxの長方形を描画

また、画像を描画したい場合は以下のようなコードになります。

canvas.js
const myCanvas = document.querySelector('#my-canvas');
const ctx = myCanvas.getContext('2d');   // 描画Contextを取得

const img = new Image(); // imageオブジェクトを新規作成
img.src = '表示したい画像のパス';
const x = 100; // x座標
const y = 150; // y座標
const width = 200; // 画像の横幅
const height = 200; // 画像の縦幅
ctx.drawImage(img, x, y, width, height);   // 画像を描画

以上になります。
canvasの使い方をもっと詳しく知りたい方は下記リンクからどうぞ。

参考:

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?