6
9

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 5 years have passed since last update.

canvasに画像を表示する

Posted at

やってみたら直感的にできなかったので少し調べました。
メモとして残しておきます。

index.html
<html>
<body>
Test<br />
<canvas id="canvas"></canvas>
</body>
<script>
    const canvas = document.getElementById("canvas");        
    let imagePath = "image.png";
    draw(canvas,imagePath);
    function draw(canvas,imagePath){
        console.log("draw");
        const image = new Image();
        image.addEventListener("load",function (){
            canvas.width = image.naturalWidth;
            canvas.height = image.naturalHeight;
            const ctx = canvas.getContext("2d");
            ctx.drawImage(image, 0, 0);
            console.log("load!");
        });
        image.src = imagePath;
    }
    </script>
</html>

idがcanvasのcanvasタグ内にimage.pngを表示させます。
試す場合は、index.htmlと同じ場所にimage.pngを適当な画像で準備してください。

addEventListenerはonloadでも問題ないですが、個人的にはaddEventListenerの方が馴染みがあるのでaddEventListenerを使っています。

6
9
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
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?