为什么这段代码没有在画布上画一个正方形?

时间:2017-09-09 18:58:17

标签: javascript html canvas

我无法理解为什么我的代码无法在画布上绘制方形边框。我刚开始学习这些东西,而且我已经忘记了一些明显的东西...

<!DOCTYPE html>
<head>
<style type="text/css">
canvas {
    background-image: url(uploads/1504975677.jpg);
    width: 500px;
    height: 334px;
}
</style>
<script type="text/javscript">
    var x = 100;
    var y = 100;
    var width = 50;
    var height = 50;
    var canvas = document.getElementById('image');
    var context = canvas.getContext('2d');

    context.strokeStyle = 'white';
    context.strokeRect(x, y, width, height);
</script>
<title>Test Website</title>
</head>
<body>
    <canvas id="image"></canvas>
</body>
</html>

为了澄清,我没有尝试为画​​布创建边框,我只想要一个未填充的框。我所得到的所有代码都是背景图像,并没有在它上面绘制任何内容。

1 个答案:

答案 0 :(得分:1)

下面应该是在关闭body标签之前放置脚本的格式,同时更改颜色:-p

<!DOCTYPE html>

<head>
  <style type="text/css">
    canvas {
      background-image: url(uploads/1504975677.jpg);
      width: 500px;
      height: 334px;
    }

  </style>
  <title>Test Website</title>
</head>

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

  <script type="text/javscript">
    var x = 100; var y = 100; var width = 50; var height = 50; var canvas = document.getElementById('image'); var context = canvas.getContext('2d'); context.strokeStyle = 'black'; context.strokeRect(x, y, width, height);
  </script>
</body>

</html>

  var x = 100; var y = 100; var width = 50; var height = 50; var canvas = document.getElementById('image'); var context = canvas.getContext('2d'); context.strokeStyle = 'black'; context.strokeRect(x, y, width, height);
canvas {
  width: 500px;
  height: 334px;
}
<canvas id="image"></canvas>