使用 HTML5 Canvas 创建图案
htmlweb developmentfront end technology更新于 2025/8/22 6:36:17
使用以下方法在 HTML5 Canvas 中创建图案:createPattern(image, repetition)− 此方法将使用图像创建图案。第二个参数可以是以下值之一的字符串:repeat、repeat-x、repeat-y 和 no-repeat。如果指定空字符串或 null,则默认为 repeat。
示例
您可以尝试运行以下代码来了解如何创建图案 −
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin: 0px auto;
}
</style>
<script>
function drawShape(){
// 使用 DOM 获取 Canvas 元素
var canvas = document.getElementById('mycanvas');
// 确保在 Canvas 不受支持时不会执行此操作
if (canvas.getContext){
// 使用 getContext 来使用画布进行绘图
var ctx = canvas.getContext('2d');
// 创建新的图像对象作为图案
var img = new Image();
img.src = 'images/pattern.jpg';
img.onload = function(){
// 创建图案
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0,150,150);
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

