canvas快速入门(四)使用重复元图像

注释很详细,直接上代码

新增内容:
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();

效果演示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码对我眨眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值