gpt4 book ai didi

javascript - 有没有一种优雅的方法可以在 Canvas 边缘绘制形状?

转载 作者:行者123 更新时间:2023-11-28 02:27:48 25 4
gpt4 key购买 nike

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

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

这是我已经拥有的:

this is what I have

这是我检查边缘的部分。

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

这就是我想要的

this is what I want

是否有一些聪明的方法可以更有效地检查这一点?我确信有一种比我目前所采用的更优雅的方法。

整个示例位于 codepen.io .

最佳答案

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

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

关于javascript - 有没有一种优雅的方法可以在 Canvas 边缘绘制形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com