[英]How to draw a rect within another one
我得到了一個基於用戶輸入的代碼,它繪制了一個矩形。 我需要在第一個矩形中創建另一個矩形,如下圖所示。
到目前為止,我得到了以下代碼。 https://codepen.io/newtz/pen/MWWKRYG
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.strokeRect(zoomedX(50), zoomedY(50), zoomed(width), zoomed(height));
}
每次畫一個矩形,你可以在里面畫一個小一點的。 例如,如果寬度和高度等於 100,那么您將調用:
context.strokeRect(0, 0, 100, 100);
然后您可以使用以前的值繪制較小的矩形:
context.strokeRect(0 + 10, 0 + 10, 100 - 20, 100 - 20);
為此,您必須為您的draw()
function 提供參數,這樣可以使 position 和新矩形的大小有所不同:
draw() => draw(x, y, width, height)
在您的代碼中,聲明兩個變量x
和y
並分配默認值(在您的代碼中為 50)。
然后你的draw()
function:
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.strokeRect(zoomedX(50), zoomedY(50), zoomed(width), zoomed(height));
}
像這樣改變:
function draw(x, y, width, height) {
context.beginPath();
context.strokeRect(zoomedX(x), zoomedY(y), zoomed(width), zoomed(height));
}
現在它有參數了。 我們還需要去掉清零指令:這個function是專門用來畫的,只有這個。 此外,如果您不刪除清除線,則每次繪制都會刪除先前繪制的矩形。
最后,在回調中調用draw(...)
函數:
$width.addEventListener("keyup", function () {
width = this.value;
context.clearRect(0, 0, canvas.width, canvas.height);
draw(x, y, width, height);
draw(x + 5, y + 5, width - 10, height - 10);
draw(x + 10, y + 10, width - 20, height - 20);
}, false);
height
相同。 因此每次更新width
或height
值時,它都會繪制 3 個嵌套矩形。
這是一個小提琴: https://jsfiddle.net/nmerinian/jzeygapL/4/
為了測試,我創建了一個drawMultiple(x, y, width, height)
function 來繪制三個矩形:
function drawMultiple(x, y, width, height) {
draw(x, y, width, height);
draw(x + 5, y + 5, width - 10, height - 10);
draw(x + 10, y + 10, width - 20, height - 20);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.