帆布重复SVG或RECT路径

发布于 2025-01-30 13:30:05 字数 498 浏览 3 评论 0原文

我需要做到这一点: bar 我尝试制作单个RECT,但我不知道如何沿X重复它。 我尝试重复一个图像(SVG),但它也行不通。 我尝试在DIV中重复背景,但结果每次都相同:空白。 我想在画布上做到这一点。 这是我的代码:

    const canvas = document.getElementById('barre');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = '../img/barre.svg';
img.addEventListener('load', ()=>{
    const ptrn = ctx.createPattern(img,'repeat-x');
    ctx.fillStyle = ptrn;
})

I need to make this: bar
I tried with making a single rect but I don't know how to repeat it along the x.
I tried repeating a image (svg) but it doesn't work too.
I tried with background repeat in a div but the result is everytime the same: blank.
I'd like to make it in canvas.
This is my code:

    const canvas = document.getElementById('barre');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = '../img/barre.svg';
img.addEventListener('load', ()=>{
    const ptrn = ctx.createPattern(img,'repeat-x');
    ctx.fillStyle = ptrn;
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡水深流 2025-02-06 13:30:05

通过将填充物分配给画布,您实际上只是在做一件事情:确定属性。在这一点上,您实际上还没有绘制任何内容。这是使用适当的图纸方法完成的。在您的情况下,fillRect()方法将非常适合。顾名思义,它绘制了一个填充的矩形。它需要四个参数的位置和尺寸。

这是一个例子:

const canvas = document.getElementById('barre');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = "";
img.addEventListener('load', () => {
  const ptrn = ctx.createPattern(img, 'repeat-x');
  ctx.fillStyle = ptrn;
  ctx.fillRect(0, 0, canvas.width, canvas.height)
});
img.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/20/30';
<canvas id="barre"></canvas>

By assigning a fillStyle to a canvas you are really just doing one thing: determining a property. At this point you are not actually drawing anything yet. This is done using the appropriate drawing methods. In your case the fillRect() method would be a perfect fit. As the name implies, it draws a filled rectangle. It takes four parameters for it's position and the dimensions.

Here's an example:

const canvas = document.getElementById('barre');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = "";
img.addEventListener('load', () => {
  const ptrn = ctx.createPattern(img, 'repeat-x');
  ctx.fillStyle = ptrn;
  ctx.fillRect(0, 0, canvas.width, canvas.height)
});
img.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/20/30';
<canvas id="barre"></canvas>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文