在Javascript中将图案绘制到矩形

时间:2019-02-07 23:01:45

标签: javascript html5-canvas

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

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

createRect()

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

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();





    }



};

1 个答案:

答案 0 :(得分:1)

我发明了一种类_Rect,用于您拥有的方法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" />