Html5-画布(canvas)之贴图的平铺模式

本文详细介绍了HTML5 Canvas中贴图的四种平铺模式:no-repeat、repeat-x、repeat-y和repeat,通过实例展示了如何使用context.createPattern()方法设置不同平铺模式,实现图像在画布上的多样化布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

贴图的平铺模式 | createPattern()
canvas/effect/pattern.html

<!DOCTYPE HTML>
<html>
<head>
<title>贴图的平铺模式</title>
</head>
<body>
<canvas id="canvas" width="620" height="620" style="background-color: rgb(222, 222, 222)">
您的浏览器不支持 canvas 标签
</canvas>
<br />
<button type="button" onclick="drawIt();">Demo</button>
<button type="button" onclick="clearIt();">清除画布</button>

<script type="text/javascript">

var ctx = document.getElementById('canvas').getContext('2d');

function drawIt() {

clearIt();

var img = new Image();
img.onload
= function () {

/*
* context.createPattern(image, repetitionStyle) - 指定贴图的平铺模式
* image - 图像对象。除了支持 HTMLImageElement 外,还支持 HTMLCanvasElement 和 HTMLVideoElement
* repetitionStyle - 平铺模式(无论任何平铺模式,首图均在画布的左上角)
* no-repeat - 不平铺,只贴图一次,当然也是在画布的左上角
* repeat-x - x 轴方向上平铺图片
* repeat-y - y 轴方向上平铺图片
* repeat - x 轴和 y 轴方向均平铺图片
*/

var pattern = ctx.createPattern(img, "no-repeat");
ctx.fillStyle
= pattern;
ctx.strokeStyle
= "blue";
ctx.beginPath();
ctx.rect(
0, 0, 300, 300);
ctx.fill();
ctx.stroke();

pattern
= ctx.createPattern(img, "repeat-x");
ctx.fillStyle
= pattern;
ctx.strokeStyle
= "blue";
ctx.beginPath();
ctx.rect(
320, 0, 300, 300);
ctx.fill();
ctx.stroke();

pattern
= ctx.createPattern(img, "repeat-y");
ctx.fillStyle
= pattern;
ctx.strokeStyle
= "blue";
ctx.beginPath();
ctx.rect(
0, 320, 300, 300);
ctx.fill();
ctx.stroke();

pattern
= ctx.createPattern(img, "repeat");
ctx.fillStyle
= pattern;
ctx.strokeStyle
= "blue";
ctx.beginPath();
ctx.rect(
320, 320, 300, 300);
ctx.fill();
ctx.stroke();
}

img.src
= "http://res2.windows.microsoft.com/resbox/en/Windows 7/main/4300ae64-546c-4bbe-9026-6779b3684fb9_0.png";
// img.src = "http://www.cnblogs.com/assets/windows_logo.png";
}

function clearIt() {
ctx.clearRect(
0, 0, 620, 620);
}

</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值