JavaScript でキャンバスに画像を読み込む 質問する

JavaScript でキャンバスに画像を読み込む 質問する

現在、要素を使用してすべての背景を描画するテストを行っています<canvas>(後でこれらの画像に効果を追加する予定なので、CSS を使用して画像をロードしていません)。ただし、現在、キャンバスに画像をロードするのに問題があります。コードは次のとおりです。

<html>    
<head>    
    <title>Canvas image testing</title>
    <script type="text/javascript">
        function Test1() {
            var ctx = document.getElementById('canvas');
            if (canvas.getContext) {
                var ctx = canvas.getContext('2d');
                //Loading of the home test image - img1
                var img1 = new Image();
                img1.src = 'img/Home.jpg';
                //drawing of the test image - img1
                img1.onload = function () {
                    //draw background image
                    ctx.drawimage(img1, 0, 0);
                    //draw a box over the top
                    ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
                    ctx.fillRect(0, 0, 500, 500);
                };
            }                
        }
    </script>
    <style type="text/css">
        canvas { border: 2px solid black; width: 100%; height: 98%; }
    </style>
</head>
<body onload="Test1();">    
    <canvas id="canvas" width="1280" height="720"></canvas>      
</body>
</html>

画像が正しく読み込まれていないと思うのですが、よく分かりません。

ベストアンサー1

いくつかあります:

  1. drawimagedrawImage正しくは「i」が大文字であることに注意してください。
  2. getElementByIdID が の要素を探していますcanvasが、 のはずですtest1canvasは ID ではなくタグです。
  3. canvas変数 (例: 行内canvas.getContext) を に置き換えますctx。これは、キャンバス要素を選択するために使用した変数です。
  4. イメージの をonload設定する前に、ハンドラーをバインドします。src

したがって、関数は次のようになります。

function Test1() {
    var ctx = document.getElementById('test1');
    if (ctx.getContext) {

        ctx = ctx.getContext('2d');

        //Loading of the home test image - img1
        var img1 = new Image();

        //drawing of the test image - img1
        img1.onload = function () {
            //draw background image
            ctx.drawImage(img1, 0, 0);
            //draw a box over the top
            ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
            ctx.fillRect(0, 0, 500, 500);

        };

        img1.src = 'img/Home.jpg';
    }
}

おすすめ記事