在画布上插入图片——要求大小、位置

在画布上绘制图片
在这里插入图片描述

<!DOCTYPE html>
<html>
<body>

<p>要使用的图片:</p>

<img src="/i/eg_tulip.jpg" alt="tulip" id="tulip" style="margin-left:0px;" />

<p>Canvas:</p>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
document.getElementById("tulip").onload=function(){
  var c=document.getElementById("myCanvas");
  var ctx=c.getContext("2d");
  
  var img=document.getElementById("tulip");
  ctx.drawImage(img,0,0,200,100,20,20,200,100);
  //(0,0)开始剪辑图像的xy坐标
  //(200,100)剪辑图像的宽,高
  //(20,20)画布上图像开始的起始坐标
  //(200,100)所要选取图像的宽度和高度,会自动对图像进行缩小扩大
};
</script>

</body>
</html>