图像填充和描边主要用到createPattern方法。
var pattern = createPattern(imageObject,repeat)
创建可重用的模式(对象);对象可以指定给任何strokeStyle或fillStyle。然后stroke()或fill()将用对象的图案绘制路径。
参数:
imageObject是将用作模式的图像。图像的来源可以是:
- HTMLImageElement --img元素或new image()生成并加载的对象
- HTMLCanvasElement --canvas元素
- HTMLVideoElement--video元素(将捕获当前视频帧)
- ImageBitmap
- Blob
repeat确定如何在画布上重复imageObject(很像CSS背景),此参数必须用引号分隔,有效值为:
- "repeat" --- 图案将水平和垂直填充画布
- "repeat-x" --- 图案只会水平重复
- "repeat-y" --- 图案只会垂直重复
- "repeat none" --- 图案只出现一次(在左上角)
pattern对象是一个可以重用的对象,使你的路径描边和填充成为有图案的。
效果演示:
<!doctype html>
<html>
<head>
<style>
body{ background-color:white; }
#canvas{border:1px solid red; }
</style>
<script>
window.onload=(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// 使用模式进行填充
var patternImage=new Image();
// 确保图像被加载
patternImage.onload=function(){
// 创建模式对象
var pattern = ctx.createPattern(patternImage,'repeat');
// 设置填充样式
ctx.fillStyle=pattern;
ctx.fillRect(20,20,280,100);
ctx.strokeRect(20,20,280,100);
}
patternImage.src='https://www.md86.net/resource/upload/20200824/5f43881577a9c6734.png';
});
</script>
</head>
<body>
<canvas id="canvas" width=325 height=250></canvas>
</body>
</html>html
效果如下: