把一幅图像放置到画布上, 使用以下方法:
drawImage(Img,x,y);
注:这里的Img必须是一个图像对象。
显示一个canvas图像:
<!DOCTYPE html>
<html>
<head>
<title>picture.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<p>画布:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
img = new Image();
img.src="scream.jpg";
img.onload = function()
{
ctx.drawImage(img,10,10);
}
</script>
</body>
</html>
注:getContext("2d");是一个内置的HTML5对象,拥有多种绘制路径、矩形、圆形及添加图形的方法。
canvas图像与<img>标签显示图像对比:
<!DOCTYPE html>
<html>
<head>
<title>picture.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<p>Image to use:</p>
<img id="scream" src="scream.jpg" alt="The Scream" width="220" height="277">
<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
img.onload = function() {
ctx.drawImage(img,10,10);
}
</script>
</body>
</html>
该文章展示了如何在HTML5的canvas元素中使用drawImage方法将图像加载并绘制到画布上。通过创建一个新的Image对象,设置其源(src)属性,然后在onload事件中调用drawImage方法,可以在指定位置(x,y)显示图像。同时,文章对比了使用canvas与<img>标签显示图像的区别。
3315

被折叠的 条评论
为什么被折叠?



