javascript canvasで画像を繰り返して表示する
- 2021.01.14
- javascript
- javascript

javascriptで、canvasタグを使用して画像を繰り返して表示するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
canvasタグ使い方
createPatternを使用すれば、画像を繰り返して表示することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** html **/ <canvas id="cvs" width="750" height="150"></canvas> /** js **/ // 2D図形を扱う const ctx = cvs.getContext('2d'); // Image オブジェクトを生成 const img = new Image; // ()を省略 // 画像を表示 img.src = '150x150.png'; // 画像読み込み完了後に描画 img.onload = () => { // 画像と繰り返し方法を指定 const pattern = ctx.createPattern(img, 'repeat'); // 塗りつぶし ctx.fillStyle = pattern; // fillRect(四角形の左上のx座標, 四角形の左上のy座標, 四角形の幅, 四角形の高さ) ctx.fillRect(0, 0, 750, 150); } |
createPattern一覧
- repeat : 水平+垂直にパターン繰り返し
- repeat-x : 水平方向にのみ繰り返し
- repeat-y : 垂直方向にのみ繰り返し
- no-repeat : 繰り返ししない
サンプルコード
以下は、
「実行」ボタンをクリックすると、画像を繰り返して表示する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。また関数もアロー関数を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> hoge = () => { // 2D図形を扱う const ctx = cvs.getContext('2d'); // Image オブジェクトを生成 const img = new Image; // ()を省略 // 画像を表示 img.src = '150x150.png'; // 画像読み込み完了後に描画 img.onload = () => { // 画像と繰り返し方法を指定 const pattern = ctx.createPattern(img, 'repeat'); // 塗りつぶし ctx.fillStyle = pattern; // fillRect(四角形の左上のx座標, 四角形の左上のy座標, 四角形の幅, 四角形の高さ) ctx.fillRect(0, 0, 750, 150); } } window.onload = () => { // クリックイベントを登録 btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略 } </script> <body> <div class="main"> <canvas id="cvs" width="750" height="150"></canvas> <button id="btn" type="button" class="btn btn-info"> 実行 </button> </div> </body> </html> |
画像が繰り返し表示されていることが確認できます。

-
前の記事
javascript メソッド名に変数を使用する 2021.01.14
-
次の記事
rails bundle install時エラー「An error occurred while installing sqlite3 (x.x.x), and Bundler cannot continue.」の対処法 2021.01.14
コメントを書く