小码哥的IT人生

HTML canvas createPattern() 方法

HTML基础 2022-06-02 15:25:32小码哥的IT人生shichen

HTML canvas createPattern() 方法

定义和用法

createPattern() 方法在指定的方向内重复指定的元素。

元素可以是图片、视频,或者其他 <canvas> 元素。

被重复的元素可用于绘制/填充矩形、圆形或线条等等。

实例

用到的图像:

lamp

在水平和垂直方向重复图像:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("lamp");
var pat=ctx.createPattern(img,"repeat");
ctx.rect(0,0,150,100);
ctx.fillStyle=pat;
ctx.fill();

 

完整实例【亲自试一试】:

<!DOCTYPE html>
<html>
<body>
<p>要用到的图片:</p>
<img src="/i/lamp.gif" id="lamp" />
<p>Canvas:</p>
<button onclick="draw('repeat')">Repeat</button>
<button onclick="draw('repeat-x')">Repeat-x</button>
<button onclick="draw('repeat-y')">Repeat-y</button>
<button onclick="draw('no-repeat')">No-repeat</button>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script type="text/javascript">
function draw(direction)
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.clearRect(0,0,c.width,c.height);
var img=document.getElementById("lamp")
var pat=ctx.createPattern(img,direction);
ctx.rect(0,0,150,100);
ctx.fillStyle=pat;
ctx.fill();
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

语法

context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");

参数值

参数 描述
image 规定要使用的图片、画布或视频元素。
repeat 默认。该模式在水平和垂直方向重复。
repeat-x 该模式只在水平方向重复。
repeat-y 该模式只在垂直方向重复。
no-repeat 该模式只显示一次(不重复)。

浏览器支持

表中的数字注明了首个完全支持该属性的浏览器版本。

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

注释:Internet Explorer 8 以及更早的版本不支持 <canvas> 元素。

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024