慕娘9325324
2023-07-29 15:14:30
我正在使用 JS 創建一個畫布,然后在所述畫布中創建一個組件,并且我希望該組件周圍有藍色邊框。我可以用 javascript 或 CSS 來做到這一點嗎?<html><head><meta name="viewport" content="width=device-width, initial-scale=1.0"/><style>canvas { border:1px solid #d3d3d3; background-color: #f1f1f1;}</style></head><body onload="startGame()"><script>var myGamePiece;function startGame() { myGameArea.start(); myGamePiece = new component(30, 30, "red", 10, 120);}var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); }}function component(width, height, color, x, y) { this.width = width; this.height = height; this.x = x; this.y = y; ctx = myGameArea.context; ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height);}</script><p>We have added a component to our game, a red square!</p></body></html>這是代碼的簡化版本。我試圖為名為 myGamePiece 的組件提供邊框。
3 回答

一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
可以使用以下方式實現邊框stroke()
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = myGameArea.context;
ctx.rect(this.x, this.y, this.width, this.height);
ctx.fillStyle = color;
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
ctx.stroke();
}

當年話下
TA貢獻1890條經驗 獲得超9個贊
由于您正在開發游戲,因此您可能希望根據游戲邏輯更改顏色屬性。最好使用 JavaScript 來實現此目的。
在之前插入以下行 -ctx.fillStyle = color;
它應該可以正常工作。
ctx.strokeStyle = 'blue'; ctx.strokeRect(this.x, this.y, this.width, this.height);
這是相同的代碼 - https://codepen.io/viveksonkar19n/pen/LYZXeEP

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
document.getElementById('your-component').style.border = 'parameters';
您可以通過在該片段中的樣式后添加正確的單詞來更改背景、文本顏色等?;蛘撸憧梢赃@樣做
.your-component { border-style: solid; border-color: blue; }
在CSS中
添加回答
舉報
0/150
提交
取消