参考书目:《HTML5 Canvas核心技术 图形、动画与游戏开发》
<!DOCTYPE html>
<html>
<head>
<title>2-6</title>
<style>
#canvas{
background: #eeeeee;
border: thin solid cornflowerblue;
}
#radios{
padding: 10px;
}
</style>
</head>
<body>
<div id="radios">
<input type="radio" id="repeatRadio" name='patternRadio' checked/>repeat
<input type="radio" id="repeatXRadio" name='patternRadio'/>repeat-x
<input type="radio" id="repeatYRadio" name='patternRadio'/>repeat-y
<input type="radio" id="noRepeatRadio" name='patternRadio'/>no repeat
</div>
<canvas id="canvas" width="1000" height="1000">
Canvas not supported
</canvas>
<script src="2-6.js"></script>
</body>
</html>
2-6.js
var canvas=document.getElementById('canvas'),
context=canvas.getContext('2d'),
repeatRadio=document.getElementById('repeatRadio'),
noRepeatRadio=document.getElementById('noRepeatRadio'),
repeatXRadio=document.getElementById('repeatXRadio'),
repeatYRadio=document.getElementById('repeatYRadio'),
image=new Image();
function fillCanvasWithPattern(repeatString) {
var pattern = context.createPattern(image,repeatString);
context.clearRect(0, 0, canvas.width,canvas.height);
context.fillStyle=pattern;
context.fillRect(0, 0, canvas.width,canvas.height);
context.fill();
}
repeatRadio.onclick=function(e){
fillCanvasWithPattern('repeat');
};
repeatXRadio.onclick=function(e){
fillCanvasWithPattern('repeat-x');
};
repeatYRadio.onclick=function(e){
fillCanvasWithPattern('repeat-y');
};
noRepeatRadio.onclick=function(e){
fillCanvasWithPattern('no-repeat');
};
image.src='e87d1a0ac24fae64a31d338ec66d83f3.png';
image.onload=function(e){
fillCanvasWithPattern('repeat');
}
效果如图所示:
网友评论