正如标题所说,我试图让绘制一个矩形图案。我创建了一个长方形的构造函数来绘制多个矩形,然后通过存放它们放入数组,以循环并调用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);
}
我发明了一种类_Rect TOR createRect()
你有方法。这个例子就不会那么上工作,但你可以看到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" />