重复纹理以循环使用clip()

Repeat texture to loop around with clip()

本文关键字:clip 循环 纹理      更新时间:2023-09-26

我有一个纹理,我在剪裁平面上使用drawImage()。但我有一个问题,当它移动超过纹理的宽度时,我不知道如何将其包裹起来,这样它就无限期地循环,而且由于某种原因,它也不会被剪裁。

我的绘图代码如下:

var radius = 120;
var pos = {'x':canvas.width/2,'y':canvas.height/2};
var x = 0;
var offsetX = 0;
function draw() {
    ctx.clearRect(0,0,canvas.width,canvas.height);
    x += 1.1415;  
    ctx.beginPath();
    ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.clip();
var scale = (radius * 2) / img.height;
    ctx.drawImage(img, pos.x+x, pos.y, img.width, img.height, pos.x - radius - offsetX * scale, pos.y - radius, img.width * scale, img.height * scale);
    ctx.restore();    
requestAnimationFrame(draw);
}

我在这里创建了演示,这样你就可以看到当纹理移动得太远时会发生什么,它基本上消失了,我需要它再次循环,没有间隙,所以它是无缝的:http://jsfiddle.net/dv2r8zpv/

绘制纹理的位置以使其环绕的最佳方法是什么,我不太明白如何做到。

我现在已经创建了一个无缝循环。我更改的代码如下。更改drawImage上的y封装整个圆圈

if (x > img.width) {
    x = 0;
}
ctx.drawImage(img, x, 0, ...);
ctx.drawImage(img, -img.width+x,0, ...);

更新了完整圆圈的答案