我想在画布上创建一个无缝模式。我将整个过程简化为简单的矩形。当一个矩形被绘制在靠近画布的边缘并且其中一部分被切断时,我希望在另一侧重复该缺失的部分。
我想我只是检查要绘制的矩形是否太靠近边缘,然后再次绘制+ canvas.width / height。中途我意识到这可能会变成很多if
。
这就是我已经拥有的:
这是我检查边缘的部分。
// this._draw(); is a convenience method that draws the rectangle with
// the center as its registration point instead of top left corner.
// which is also why I add (this.size/2) to the coordinates.
if(this.x+( this.size/2 ) > canvas.width) {
this._draw(
this.x+canvas.width,
this.y
);
}
if(this.x-( this.size/2 ) < 0){
this._draw(
this.x+canvas.width,
this.y
);
}
if(this.y+( this.size/2 ) > canvas.height) {
this._draw(
this.x-(this.size/2),
this.y-canvas.height-(this.size/2)
)
}
if(this.y-(this.size/2) < 0){
this._draw(
this.x,
this.y+canvas.height
);
}
这就是我想要的
有更聪明的方法来更有效地检查这个吗?我确信有一种比我目前所指的更优雅的方法。
整个示例位于codepen.io。
答案 0 :(得分:1)
<强> Take a look at this code 强>:
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var LT = new Dot(0, 100, 290, 140);
var RT = new Dot(90, 75, canvas.width, 0);
var RB = new Dot(180, 50, canvas.width, canvas.height);
var LB = new Dot(270, 25, 0, canvas.height);
function Dot(color, size, x, y){
this.size = size;
this.x = x;
this.y = y;
this.color = "hsla("+color+", 100%, 50%, 1)";
this.draw = function() {
context.fillStyle = this.color;
context.strokeStyle = "hsla(0,0%,0%, 0.5)";
this._draw(x, y);
this.drawBorders();
};
this._draw = function(centerX, centerY) {
context.fillRect(
centerX - size/2,
centerY - size/2,
size,
size
);
};
this.drawBorders = function() {
var borders = 0;
var tx, ty;
if(x - size/2 <= 0){
tx = canvas.width + x;
}else if(x + size/2 >= canvas.width){
tx = canvas.width - x;
}
if(y - size/2 <= 0){
ty = canvas.height + y;
}else if(y + size/2 >= canvas.height){
ty = y - canvas.height ;
}
if(x-size/2 <= 0 || x+size/2 >= canvas.width ){
this._draw(tx, y);
}
if(y-size/2 <= 0 || y+size/2 >= canvas.height){
this._draw(x, ty);
}
if(x+size/2 >= canvas.width ||
y+size/2 >= canvas.height ||
x-size/2 <= 0 ||
y-size/2 <= 0){
this._draw(tx, ty);
}
}
this.draw();
}
document.body.appendChild(canvas);
这会将方块绘制成与角重叠,但前提是它们确实重叠。