注释很详细,直接上代码
新增内容:
1. 使用重复元图像渲染矩形
2. 重复的四种不同方式
项目结构:

源码:
index.html
<!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>
<style>
*{
margin: 0;
padding: 0;
}
</style>
<body>
</body>
<script src="./js/canvas.js"></script>
</html>
canvas.js
/**
* 创建画布
* @param {number} width - 宽度
* @param {number} height - 高度
* @returns {HTMLCanvasElement} -返回画布
*/
function createCanvas(width, height) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
document.body.append(canvas);
return canvas;
}
/**
* 使用重复元图像填充矩形
* @param {HTMLCanvasElement} canvas - 画布
* @param {string} imgUrl - 图像地址
* @param {number} x - 矩形左上角x坐标
* @param {number} y - 矩形左上角y坐标
* @param {number} width - 矩形宽度
* @param {number} height - 矩形高度
* @returns {void} - 无返回值
*/
function fillRectWithPattern(canvas, imgUrl, x, y, width, height) {
const ctx = canvas.getContext("2d");
//创建图像
const img = new Image();
img.src = imgUrl;
//创建重复图像
const pattern = ctx.createPattern(img, "repeat"); // 'repeat', 'repeat-x', 'repeat-y', 'no-repeat' 可选
//设置填充颜色
ctx.fillStyle = pattern;
//绘制矩形
ctx.fillRect(x, y, width, height);
}
/**
* 开始
* @returns {void} - 无返回值
*/
function start() {
const canvas_1 = createCanvas(800, 800);
let imgUrl =
"http://hbimg.huaban.com/c59d61c55ef32403e4011882247f1923f2a81bcddab3-a9fnjP";
fillRectWithPattern(canvas_1, imgUrl, 0, 0, 800, 800);
}
start();
效果演示:

84

被折叠的 条评论
为什么被折叠?



