【问题标题】:How to draw a colored square on event change using canvas如何使用画布在事件更改上绘制彩色方块
【发布时间】:2020-01-12 14:34:33
【问题描述】:

我想在它旁边弹出一个蓝色方块。我希望这是一个持续的过程

让我们将按钮点击视为创建一个新框(例如红色、蓝色和黄色按钮)的事件,点击它会产生一个,然后在它旁边产生另一个,依此类推。

我已经尝试过同时使用 DOM 和 CSS 来做到这一点,但由于我的编程知识并不好,因此无济于事。我可能尝试过以 div 的形式附加孩子(我不确定它是如何工作的)。

我希望输出是不同颜色的小方块,当它识别事件(例如按钮单击)时,使用画布将其粘贴在屏幕上。这个我稍后会尝试适应人脸识别。

我必须做什么才能达到这个结果?

理论结果: https://i.imgur.com/M5cwVqx.png

如果可能,我希望它在到达边缘屏幕时从头开始循环,以便最终填满整个画布。谢谢。

【问题讨论】:

    标签: javascript dom canvas html5-canvas


    【解决方案1】:

    您可以在 html 中放置一个简单的画布,这样您就可以使用 javascript 在里面进行绘制。

    你可以在这里找到一个很好的教程https://www.w3schools.com/graphics/canvas_intro.asp

    const lengthSquare = 50, marginSquare = 10, colors = ["red", "blue", ""];
    var x = marginSquare, y = marginSquare;
    var canvas = document.getElementById("myCanvas");
    var width = canvas.width, height = canvas.height;
    var ctx = canvas.getContext("2d");
    
    var addSquare = function(color){
      if(y + lengthSquare > height){
      	console.error("Too much squares");
        return;
      }
      ctx.beginPath();
      ctx.strokeStyle = color;
      ctx.lineWidth = 3;
      ctx.strokeRect(x,y,lengthSquare,lengthSquare);
      ctx.stroke();
      x += marginSquare + lengthSquare;
      if(x + lengthSquare > width){
      	x = marginSquare;
        y += marginSquare + lengthSquare;
      }
    }
    <!DOCTYPE html>
    <html>
    <body>
    
    <input type="button" onclick="addSquare('red')" value="AddSquare RED"/>
    <input type="button" onclick="addSquare('yellow')" value="AddSquare YELLOW" />
    <input type="button" onclick="addSquare('blue')" value="AddSquare BLUE" />
    <br />
    <canvas id="myCanvas" width="500" height="200" style="border:2px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多