我几周前开始对HTML5进行编程,现在我实际上在学习更多有关画布的知识,第一个练习是创建一个矩形并将其填充到js中。但是,这似乎行不通。问题出在哪里?
代码:
<head>
<title>Canvas Exercise</title>
<script type="text/javascript">
myCanvas = document.getElementById("canvasTry");
context = myCanvas.getContext("2d");
context.fillStyle = "#FF0000";
context.fillRect = (10,10,150,150);
</script>
</head>
<body>
<canvas id="canvasTry" width="300px" height="150px" style="border:2px solid black">
!! IF YOU READ THIS, YOUR BROWSER DO NOT SUPPROT CANVAS !!
</canvas>
</body>
答案 0 :(得分:1)
将脚本放置在页面底部。因为它是您的脚本在画布存在之前运行
此外,fillRect
是一个函数
如此
context.fillRect = (10, 10, 150, 150); // bad!!
context.fillRect(10, 10, 150, 150); // good
固定
<head>
<title>Canvas Exercise</title>
</head>
<body>
<canvas id="canvasTry" width="300px" height="150px" style="border:2px solid black">
!! IF YOU READ THIS, YOUR BROWSER DO NOT SUPPROT CANVAS !!
</canvas>
</body>
<script>
myCanvas = document.getElementById("canvasTry");
context = myCanvas.getContext("2d");
context.fillStyle = "#FF0000";
context.fillRect(10,10,150,150);
</script>
工作示例
<head>
<title>Canvas Exercise</title>
</head>
<body>
<canvas id="canvasTry" width="300px" height="150px" style="border:2px solid black">
!! IF YOU READ THIS, YOUR BROWSER DO NOT SUPPROT CANVAS !!
</canvas>
</body>
<script>
myCanvas = document.getElementById("canvasTry");
context = myCanvas.getContext("2d");
context.fillStyle = "#FF0000";
context.fillRect(10,10,150,150);
</script>
其他一些事情
画布的宽度和高度是数字
<canvas width="300px" height="150px" // BAD!!
<canvas width="300" height="150" // Good
它起作用是因为浏览器忽略了px
您不需要type="text/javascript"
<script>
...code...
</script>
工作正常
您真的不需要画布内的警告
<canvas...>
!! IF YOU READ THIS, YOUR BROWSER DO NOT SUPPROT CANVAS !!
</canvas>
现在是2018年。实际上没有不支持画布的浏览器。