HTML5 drawImage()方法将图像绘制到画布上

要将图像绘制到画布上,请使用HTML5drawImage()方法:

<!DOCTYPE HTML>
<html>
   <head>
      <script>
         function drawShape(){
            //使用DOM获取canvas元素
            var canvas = document.getElementById('mycanvas');
         
            //确保不支持画布时不执行
            if (canvas.getContext){
               //使用getContext将画布用于绘制
               var ctx = canvas.getContext('2d');
               //绘制形状
               var img = new Image();
               img.src = '/images/backdrop.jpg';

               img.onload = function(){
                  ctx.drawImage(img,0,0);
                  ctx.beginPath();
                  ctx.moveTo(30,96);
                  ctx.lineTo(70,66);
                  ctx.lineTo(103,76);
                  ctx.lineTo(170,15);
                  ctx.stroke();
               }
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   <body onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
</html>