canvas 的createPattern 属性支持svg、img等元素的重复绘制。下面写个绘制canvas 元素的例子,网状表格画起来
实现上述网格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="mycanvas" width="511px" height="511px">您的浏览器不支持canvas</canvas>
</body>
<script>
function drawCanvas(){
var canvas = document.createElement("canvas");
canvas.width = 20
canvas.height = 20
var ctx = canvas.getContext('2d')
ctx.translate(.5, .5)
ctx.beginPath();
ctx.moveTo(10, 0)
ctx.lineTo(10, 20)
ctx.moveTo(0, 10)
ctx.lineTo(20, 10);
ctx.stroke();
return canvas
}
function drawPattern(target,repeat) {
// 创建CanvasPattern对象
var canvas1 = document.getElementById("mycanvas");
var contast = canvas1.getContext('2d')
contast.translate(-10, -10)
let pattern = contast.createPattern(target, repeat);
// 将新创建的CanvasPattern对象赋值给fillStyle属性
contast.fillStyle = pattern;
// 清除画布
contast.clearRect(0, 0, canvas1.width, canvas1.height);
// 绘制图案
contast.fillRect(0, 0, canvas1.width, canvas1.height);
}
drawPattern(drawCanvas(),'repeat');
</script>
</html>
以上就是createPattern 属性的重复绘制了