admin管理员组文章数量:1405513
I'm playing with HTML5 canvas element with JavaScript. Now I can draw shapes to the canvas with internal JavaScript when I create an external file I get an Uncaught Type Error
. All I want to do is draw a rectangle to my canvas through an external file.
Here is my HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FireBlaster</title>
</head>
<body style="background:#111111">
<div id="inner">
<button id="drawSquareBtn" type="button">Draw Square</button>
<canvas id="myCanvas" width="600px" ; height="400px;" style=" dispaly:block; background:#000000; margin:8% 25%;"></canvas>
</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
This is my JavaScript:
//JavaScript Document
var canvasBg = document.getElementById('myCanvas');
var ctx = canvasBg.getContext('2D');
function drawSquare() {
alert('your pressed a button!');
ctx.fillStyle = "#0A0AFF";
ctx.fillRect(200, 150, 150, 50);
}
var drawSquareBtn = document.getElementById('drawSquareBtn');
drawSquareBtn.addEventListener('click', drawSquare, false);
I'm playing with HTML5 canvas element with JavaScript. Now I can draw shapes to the canvas with internal JavaScript when I create an external file I get an Uncaught Type Error
. All I want to do is draw a rectangle to my canvas through an external file.
Here is my HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FireBlaster</title>
</head>
<body style="background:#111111">
<div id="inner">
<button id="drawSquareBtn" type="button">Draw Square</button>
<canvas id="myCanvas" width="600px" ; height="400px;" style=" dispaly:block; background:#000000; margin:8% 25%;"></canvas>
</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
This is my JavaScript:
//JavaScript Document
var canvasBg = document.getElementById('myCanvas');
var ctx = canvasBg.getContext('2D');
function drawSquare() {
alert('your pressed a button!');
ctx.fillStyle = "#0A0AFF";
ctx.fillRect(200, 150, 150, 50);
}
var drawSquareBtn = document.getElementById('drawSquareBtn');
drawSquareBtn.addEventListener('click', drawSquare, false);
Share
Improve this question
edited Mar 18, 2018 at 1:08
sg7
6,2982 gold badges34 silver badges41 bronze badges
asked Dec 24, 2012 at 14:30
MattyMatty
151 gold badge2 silver badges8 bronze badges
2 Answers
Reset to default 3The d in getContext("2d")
needs to be lower case.
Live Demo
// Changed d to lower case
var ctx = canvasBg.getContext('2d');
Wrong : -- var ctx = canvasBg.getContext('2D');
Right :-- var ctx = canvasBg.getContext('2d');
D
capital does not create instance.
本文标签: htmlUncaught Type Error Cannot set property of 39fillStyle39 of null HTML5 JavascriptStack Overflow
版权声明:本文标题:html - Uncaught Type Error: Cannot set property of 'fillStyle' of null HTML5 Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744921914a2632345.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论