html5 canvas學習--操作與使用影象

xiaopengyaonixi發表於2016-10-07

// 1.建立image物件

var img = new Image();

// 2.設定image物件的onload屬性

img.onload = function(){

}

// 3.繪製影象

context.drawImage(image,x,y);

context.drawImage(image,x,y,width,height);

context.drawImage(image,x,y,sWidth,sHeight,dx,dy,dWidth,dHeight);// sWidth和sHeight是剪裁下來的寬度和高度,dx和dy為裁剪後圖片放置的位置,dWidth和dHeight為顯示圖片的大小.

一.繪製圖片並改變圖片的大小

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<script type="text/javascript">
		function draw(){
			var ctx = document.getElementById("myCanvas").getContext("2d");
			var img = new Image();
			img.onload = function(){
				ctx.drawImage(img,0,0,100,100);
				ctx.font = "italic 60px Arial Black";
				ctx.shadowOffsetX = 3;
				ctx.shadowOffsetY = 3;
				ctx.shadowBlur = 2;
				ctx.shadowColor = "rgba(0,0,0,0.7)";
				ctx.fillStyle = "Green";
				ctx.fillText("javascript !",50,165);
			}
			img.src = "1.ico";
		}
		window.onload = function(){
			draw();
		}
	</script>
</head>
<body>
	<canvas id="myCanvas" width="600" height="200"></canvas>
</body>
</html>

二.裁切圖片

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<script type="text/javascript">
		function draw(){
			var ctx = document.getElementById("myCanvas").getContext("2d");
			var img = new Image();
			img.onload = function(){
				ctx.drawImage(img,0,0);
				ctx.drawImage(img,10,10,100,100,0,0,100,100);
			}
			img.src = "logo.png";
		}
		window.onload = function(){
			draw();
		}
	</script>
</head>
<body>
	<canvas id="myCanvas" width="1200" height="600"></canvas>
</body>
</html>



相關文章