1

我想在画布上创建无缝图案。我将整个过程简化为简单的矩形。当靠近画布边缘绘制一个矩形并且它的一部分被切断时,我希望在另一侧重复缺失的部分。

我想我只是检查要绘制的矩形是否离边缘太近,然后再次绘制+canvas.width/height。中途我意识到这可能会变成相当多if的 s。

这是我已经拥有的:

这就是我所拥有的

这是我检查边缘的部分。

// 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上。

4

1 回答 1

1

看看这段代码

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

这会将正方形绘制为与角重叠,但前提是它们确实重叠。

于 2013-02-01T09:13:04.997 回答