我对 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>