在画布上以响应高度重复图像

时间:2019-06-17 20:03:49

标签: javascript html css canvas

我正在尝试创建一个画布,其中我有一个图像作为背景,该图像水平重复并自动调整高度。

我设法沿x轴重复了背景图像,但无法使高度响应。

到目前为止,这是我的代码:

const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");

const bg = new Image();
bg.src = "http://lorempixel.com/100/100";

const draw = () => {
  const ptrn = ctx.createPattern(bg, "repeat-x");
  ctx.fillStyle = ptrn;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  requestAnimationFrame(draw);
};

draw();
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
</head>

<body>
  <canvas id="canvas" width="1000" height="200"></canvas>
  <script src="index.js"></script>
</body>

</html>


  

TLDR :我希望能够在画布中具有水平重复的图像,并且其高度可以响应。

谢谢。

3 个答案:

答案 0 :(得分:1)

希望评论中的解释回答您的问题。随时要求澄清。

const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");

// First stretch the canvas so we can get 
// the full size of teh browser window
cvs.style.height = '100vh';
cvs.style.width = '100vw';

// Now adjust actual canvas size to match
const {width, height} = cvs.getBoundingClientRect();
cvs.height = height;
cvs.width = width;

const bg = new Image();

// Should always wait for onload 
// before drawing to prevent race condition.
bg.onload = ()=>{

  var x=0;
  while(x < cvs.width){
    ctx.drawImage(bg, x, 0, 100, cvs.height);
    x += bg.width;
  }

  // draw the image a bunch of times
  // var x=0, y=0;
  // while(x < cvs.width && y < cvs.height){
  //   ctx.drawImage(bg, x, y);
  //   x += bg.width;
  //   if(x > cvs.width){
  //     x = 0;
  //     y += bg.height;
  //   }
  // }

};
bg.src = "http://lorempixel.com/100/100";
<canvas id="canvas"></canvas>
<script src="index.js"></script>

答案 1 :(得分:1)

如果我做对了,您想要填充高度并水平重复,那是正确的吗?

const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");

var bg = new Image();
bg.src = "http://lorempixel.com/100/100";

var tempCanvas = document.createElement("canvas"),
    tCtx = tempCanvas.getContext("2d");

var imgWidth = 200;
var imgHeight = 200;

const draw = () => {
  tempCanvas.width = imgWidth;
  tempCanvas.height = imgHeight;
  tCtx.drawImage(bg, 0, 0, 100, 100, 0, 0, imgWidth, imgHeight);
  const ptrn = ctx.createPattern(tempCanvas , "repeat-x");
  ctx.fillStyle = ptrn;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  requestAnimationFrame(draw);
};
bg.onload = () => {
  draw();
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
</head>

<body>
  <canvas id="canvas" width="1000" height="200"></canvas>
  <script src="index.js"></script>
</body>

</html>

答案 2 :(得分:0)

尝试像这样设置图像尺寸以匹配画布尺寸:

bg.src =“ http://lorempixel.com/200/200”;

干杯! :)