【问题标题】:How do I get a border around a component element ina canvas with javascript? [duplicate]如何使用 javascript 在画布中的组件元素周围设置边框? [复制]
【发布时间】:2020-11-11 08:51:38
【问题描述】:

我正在使用 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 的组件,我试图给它一个边框。

【问题讨论】:

  • 你可以使用像component = document.getElementById('component')component.style.border = '2px solid red'这样的JS 如果你可以发布你的代码,我可能会为你的用例给你一个更详细的答案
  • 不太清楚我如何在评论中回复代码,但我用一些代码编辑了原始帖子。感谢您的提示,如果我找不到解决此问题的其他方法,可以试试这个。
  • 别担心,我用你的组件函数的修改版本发布了答案

标签: javascript html5-canvas


【解决方案1】:

可以使用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();
}

【讨论】:

    【解决方案2】:

    由于您正在开发游戏,因此您可能希望根据游戏逻辑更改颜色属性。最好使用 JavaScript。

    在下面的行之前插入 - ctx.fillStyle = color; 它应该可以正常工作。

    ctx.strokeStyle = 'blue';
    ctx.strokeRect(this.x, this.y, this.width, this.height);
    

    这是相同的代码 - https://codepen.io/viveksonkar19n/pen/LYZXeEP

    【讨论】:

      【解决方案3】:
      document.getElementById('your-component').style.border = 'parameters';
      

      您可以通过在该 sn-p 中的样式后添加正确的单词来更改背景、文本颜色等。或者,你可以这样做

      .your-component {
      border-style: solid;
      border-color: blue;
      }
      

      在css中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        • 2020-12-04
        • 2011-07-23
        相关资源
        最近更新 更多