0
我超級堅持這一點,到目前爲止我所做的是創建隨機大小的直角座標的函數,它出現在畫布的隨機位置。我需要做的是使用JS繪製矩形,每當我創建一個新的,它不能與現有的衝突。onclick在畫布上創建隨機矩形,不會與現有的矩形衝突
<!DOCTYPE html>
<html>
<head>
<title>rectangles sucks</title>
</head>
<body>
<button id="buttonxD">press me!</button>
<script>
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.height = 500;
canvas.width = 500;
var context = canvas.getContext("2d");
body.appendChild(canvas);
function create() {
// Opacity
context.globalAlpha=0.7;
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = color;
//Each rectangle's size is (20 ~ 100, 20 ~ 100)
context.fillRect(Math.random()*canvas.width, Math.random()*canvas.width, Math.random()*80+20, Math.random()*80+20);
}
document.getElementById('buttonxD').addEventListener('click', create);
</script>
</body>
</html>
我看到這個功能用來檢查碰撞檢測
function isCollide(a, b) {
return !(
((a.y + a.height) < (b.y)) ||
(a.y > (b.y + b.height)) ||
((a.x + a.width) < b.x) ||
(a.x > (b.x + b.width))
);
}
但我沒有將它集成到我的代碼... 任何想法,我應該用我現有的代碼做什麼不同的,任何事情都會有幫助,謝謝