首页 > 解决方案 > 在Javascript中将图案绘制到矩形

问题描述

正如标题所说,我正在尝试将图案绘制到矩形上。我创建了一个矩形构造函数来绘制多个矩形,然后将它们存储在一个数组中,以便循环调用该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();





    }



};

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

//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);
    }

标签: javascripthtml5-canvas

解决方案


我发明了一个类 _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" />

推荐阅读