如标题所示,我正在尝试将图案绘制到矩形上。我创建了一个矩形构造函数来绘制多个矩形,
然后将它们存储在数组中以循环遍历并调用createRect()函数。

问题是,帆布最终完全变成黑色。

var canvas = document.getElementById("slideshow");
var ctx = canvas.getContext("2d");
var img = [];
var img_height = 380;
var img_length = 475.75;









function picture(){


this.img_height = img_height;
this.img_length = img_length;
this.X = 0;


this.getX = function(num) {

    switch(num){

    case 1:
        break;
    case 2:
        this.X = this.img_length;
        break;
    case 3:
        this.X = this.img_length * 2;
        break;
    case 4:
        this.X = this.img_length * 3;
        break;
    case 5:
        this.X = -this.img_length;
        break;
    };




};

this.createRect = function(num){

    this.obj = document.getElementById('p' + num);
    this.pattern = ctx.createPattern(this.obj, 'no-repeat');
    ctx.fillStyle = this.pattern;

    ctx.beginPath();
    ctx.fillRect(this.X, 0, this.img_length,this.img_height);
    ctx.fill();





    }



};


Theser是创建每个对象并显示它们的循环。

//Create objects
for(let i = 0;i<=5;i++)
    {
        img[i-1] = new picture();
    }

//get x coords and display
for(let i = 0;i<5;i++)
    {
        img[i].getX(i+1);
        img[i].createRect(i+1);
    }

最佳答案

我发明了一个类_Rect tor createRect()。该示例不适用于SO,但您可以在codepen上看到一个有效示例

请确保您使用的是来自同一域的图像。

 

let ctx = canvas.getContext("2d")

class _Rect{
  constructor(o){
    this.X = o.x;
    this.y = o.y;
    this.img_length = o.w;
    this.img_height = o.h
  }

  createRect() {
  this.object = document.getElementById('p1');
  this.pattern = ctx.createPattern(this.object, 'no-repeat');
  ctx.fillStyle = this.pattern;
  ctx.beginPath();
  ctx.fillRect(this.X, 0, this.img_length, this.img_height);
  ctx.strokeRect(this.X, 0, this.img_length, this.img_height);
};
}


canvas{border:1px solid}


<canvas id="canvas" width="300" height="300"></canvas>
<img id="p1" src="pin.png" />

09-26 22:44
查看更多