javascript - 颜色未显示在 Javascript Canvas 中

标签 javascript canvas colors

我一直在关注这个教程:https://www.youtube.com/watch?v=VLpjfr7mgT0I关于用 Javascript 制作游戏。我想在我的网页中测试它,但是 Canvas 没有颜色,尽管它应该有边框和黑色矩形。我不知道我应该做什么,所以我希望有人可以帮助我修复此代码,以便它可以在我的网页中运行。代码:

<!doctype html>
<html>
<body>
<head>

<canvas id = "canvas" width = "640" height = "480">
style = "border:1px solid gray; width: 640px; height: 480px;">
</canvas>

<script>
var Context = {
    canvas : null,
    context : null,
    create: function(canvas_tag_id) {
        this.canvas = document.getElementById(canvas_tag_id);
        this.context = this.canvas.getContext('2d');
        return this.context;
    }

};

$(document.ready(function){


   Context.create("canvas");

   Context.context.beginPath(); 
   Context.context.rect(0, 0, 640, 480);
   Context.context.fillStyle = 'black';
   Context.context.fill();

   // Context.context.beginPath();



});
</head>
</script>
</body>
</html>

谢谢!

最佳答案

嗯,我发现了大约 6-7 个不同的错误,其中大多数是坏的应答器叠瓦/位置问题,并且您没有在脚本中包含 jQuery...

这是一个工作示例,尝试将其与您的代码进行比较以了解问题所在。

<!doctype html>
<html>

<head>
  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
</head>
<body> 
  <canvas id = "canvas" width = "640" height = "480" style = "border:1px solid gray; width: 640px; height: 480px;">
  </canvas>

  <script>
    var Context = {
      canvas : null,
      context : null,
      create: function(canvas_tag_id) {
        this.canvas = document.getElementById(canvas_tag_id);
        this.context = this.canvas.getContext('2d'); 
        return this.context;
      }
    };

    $(document).ready(function() {
      Context.create("canvas");
      Context.context.beginPath();
      Context.context.rect(0, 0, 640, 480);
      Context.context.fillStyle = 'black';
      Context.context.fill();
    });
  </script>
</body>
</html>

关于javascript - 颜色未显示在 Javascript Canvas 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35850779/

相关文章:

javascript - 为什么 coffeescript 会覆盖我的下划线?

javascript - 检查一个点是否穿过一条线

linux - Bash 和对话框 UI,如何动态改变颜色

c# - 不着色,但 "Colorize" Sprite

java - 为 View 的填充着色

javascript - 通过鼠标拖动创建多边形形状不会使形状以其选择边框框为中心

javascript - 未定义元素

javascript - 可调整大小的元素边框

javascript - 未捕获的类型错误 : Cannot read property 'canvas' of undefined - Javascript Object

python - 将图像渲染为定义的像素方 block HTML5 Canvas ?