我对javascript完全陌生,但对编程却不了解。。。对于我一生,我无法弄清楚。我正在尝试在画布上绘制图像。我可以绘制一个矩形,但不能绘制图像。

这是我的代码:

<head>
    <meta http-equiv = "Content-type" content = "text/html;charset=utf-8">
    <meta name = "viewport" id = "viewport" content = "width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;"/>
    <script type = "text/javascript">
        function drawPic()
        {
            ////////////// DOESN'T WORK ///////////////////
            var canvas = document.getElementById('mainCanvas');
            if (canvas.getContext)
            {
                var context = canvas.getContext('2d');
                var img = new Image();
                img.onload = function ()
                {
                    canvas.drawImage(img, 0, 0);
                };
                img.src = "pic1.jpg";
            }


            ///////////////////////////////////////////////////////////////
            ///////////// WORKS //////////////////////////////////////////
            if (canvas.getContext)
            {
                var context = canvas.getContext('2d');
                context.fillStyle = "rgb(150,29,28)";
                context.fillRect(2, 2, 96, 96);
            }
        }
    </script>
</head>
<body onload = "drawPic();">
    <canvas id = "mainCanvas"></canvas>
</body>

最佳答案

而不是canvas.drawImage(img, 0, 0);应该在context-context.drawImage(img, 0, 0);上调用。希望能帮助到你 :)

10-07 20:05
查看更多