如何解决如何使用JavaScript在画布中的组件元素周围设置边框?
我正在用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。
解决方法
可以使用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();
}
,
由于您在开发游戏,因此可能要根据游戏逻辑更改颜色属性。最好为此使用JavaScript。
在下面的行之前插入-ctx.fillStyle = color;
,应该可以。
ctx.strokeStyle = 'blue';
ctx.strokeRect(this.x,this.height);
这里是相同的代码-https://codepen.io/viveksonkar19n/pen/LYZXeEP
,document.getElementById('your-component').style.border = 'parameters';
您可以更改背景,文本颜色等,只需在该代码段中的样式后添加正确的单词即可。或者,您可以
.your-component {
border-style: solid;
border-color: blue;
}
在CSS
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。