提问者:小点点

图标单击以JavaScript在画布上绘制矩形


在HTML和JavaScript中,这应该是一个非常简单的任务。我有一个图标栏,目前有一个单一的可点击链接,新的框。在图标栏下面,我有一张画布。我的目标是在用户每次按下new Box按钮时,在画布上绘制一个新的矩形。

现在,我的图标栏和画布正确显示,我可以单击图标栏的“新建框”链接,但画布上没有出现矩形,尽管我已将其onclick参数指定为:NewBox

null

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

function newBox(e) {
  context.beginPath();
  context.fillStyle = "#ADD8E6";
  context.fillRect(50, 50, 150, 150);
  context.fill();
}
body{
  background-color: ivory;
  padding:20px;
}

.icon-bar {
  width: 100%; 
  background-color: #555; 
  overflow: auto; 
  margin-bottom: 25px;
}

.icon-bar a {
  float: left;
  text-align: center;
  width: 11.11%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 24px;
  text-decoration: none;
}

.icon-bar a:hover {
  background-color: #000; 
}

.icon-bar-text {
  font-style: normal;
}

.active {
  background-color: #4CAF50; 
}

#canvas {
  width:95%;
  height:30%;
  border:4px solid blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Builder</title>
    <link rel="stylesheet" type="text/css" media="all" href="style.css" />
    <script src="script.js"></script>
</head>
<body>
    <div class="icon-bar">
        <a href="#">
          <i class="icon-bar-text" onclick="newBox();" title="Click to add a new box on canvas">New Box
          </i>
        </a>
       <!-- ...there will be more <a> tags here -->
    </div>

    <canvas id="canvas"></canvas>
</body>
</html>

null


共1个答案

匿名用户

您需要存储和更新y位置,如下所示。请注意,您还需要增加画布的大小,以防止框消失。

null

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

let prevY = 0;

function newBox(e) {
  context.fillStyle = "#ADD8E6";
  context.fillRect(50, prevY, 150, 150);
  prevY+= 160; // height + some padding
}
body {
  background-color: ivory;
  padding: 20px;
}

.icon-bar {
  width: 100%;
  background-color: #555;
  overflow: auto;
  margin-bottom: 25px;
}

.icon-bar a {
  float: left;
  text-align: center;
  width: 11.11%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 24px;
  text-decoration: none;
}

.icon-bar a:hover {
  background-color: #000;
}

.icon-bar-text {
  font-style: normal;
}

.active {
  background-color: #4CAF50;
}
<div class="icon-bar">
  <a href="#"><i class="icon-bar-text" onclick="newBox();" title="Click to add a new box on canvas">New Box</i></a>
  <!-- ...there will be more <a> tags here -->
</div>

<canvas id="canvas" width="500" height="500"></canvas>