代码示例:
createPattern
createPattern可以以另一个canvas作为填充
createPattern用图片填充
createPattern(video,repeat-style)
createPattern甚至还有嵌入video的能力
createPattern(canvas.repeat-style);
createPattern的功能十分强大,可以引入其他的canvas;
实际例子中,使用new Image() 创建一个图片对象,并且给src赋值提供路径
createPattern(img,repeat-style); repeat-style:no-repeat repeat-x repeat-y repeat
全部代码,不谢
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas</title>
</head>
<body>
<canvas id="canvas" width="1024" height="768" style="border:1px solid;"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas');
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext('2d');
// createPattern(img, repeat-style);
// repeat-style: no-repeat/repeat-x/repeat-y/repeat
// var bgImg = new Image();
// bgImg.src = 'https://img1.mukewang.com/5333a1bc00014e8302000200-140-140.jpg';
// bgImg.onload = function () {
// var pattern = context.createPattern(bgImg, 'repeat');
// context.fillStyle = pattern;
// context.fillRect(0, 0, 800, 800);
// }
var bgCanvas = createBackgroundCanvas();
var pattern = context.createPattern(bgCanvas, 'repeat');
context.fillStyle = pattern;
context.fillRect(0, 0, 800, 800);
function createBackgroundCanvas() {
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext('2d');
drawStar(context, 50, 50, 50, 0); // 之前的课程中写的的
return canvas;
}
function drawStar(ctx, x, y, R, rot) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(rot/180*Math.PI);
ctx.scale(R, R);
starPath(ctx);
ctx.fillStyle = '#fb3';
ctx.fill();
ctx.restore();
}
function starPath(ctx) {
ctx.beginPath();
for (var i = 0; i < 5; i++) {
ctx.lineTo(Math.cos((18+i*72)/180*Math.PI),
-Math.sin((18+i*72)/180*Math.PI));
ctx.lineTo(Math.cos((54+i*72)/180*Math.PI)*0.5,
-Math.sin((54+i*72)/180*Math.PI)*0.5);
}
ctx.closePath();
}
</script>
</html>