请有人帮助我!我是javascript的新手。 我想用javascript制作画布动画。但是我有以下错误 SCRIPT5007:无法获取属性'getContext'的值:object为null或undefined drawing_script.js,第31行第5个字符 这是代码。 使用Javascript:
// JScript source code
/*
Because the canvas can hold only one context at time, we'll create two canvas. Each one with its context.
One canvas for the circle, and another one for the square.
*/
var canvasCircle;
var contextCircle;
var x = 400;
var y = 300;
var dx = 2;
var WIDTH = 800;
var HEIGHT = 600;
// the circle wont make any transsformation.
function draw_circle(x, y, r) {
contextCircle.beginPath();
contextCircle.arc(x, y, r, 0, 2 * Math.PI, true);
contextCircle.closePath();
contextCircle.stroke();
}
function clear_canvas() {
contextCircle.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
//canvasCircle = document.getElementById("canvas_circle");
canvasCircle = document.getElementById("canvas_circle");
contextCircle = canvasCircle.getContext('2d');
return setInterval(draw, 10);
}
function draw() {
// clear_canvas();
draw_circle(x, y, 50);
// if (x + dx > WIDTH || x + dx < 0)
// dx = -dx;
// x += dx;
}
init();
HTML5:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="Scripts/drawing_script.js" language="javascript"></script>
<title>Blackberry</title>
</head>
<body>
<div class="drawing" style="background:Green">
<canvas id="canvas_circle" width="800" height="600"></canvas>
答案 0 :(得分:3)
这是因为您在创建画布之前执行脚本。
创建canvas元素FIRST然后嵌入javascript。
IE:canvasCircle是未定义的,因为你无法通过不存在的ID获取元素!
答案 1 :(得分:1)
我找到了答案:init()应该是 function init(){ s_canvas = document.getElementById(“canvas_square”); //检查画布是否受支持以及getContext是否可用 if(s_canvas&amp;&amp; s_canvas.getContext){ s_context = s_canvas.getContext(“2d”); return setInterval(draw,10); } 其他{ alert(“不支持Canvas!”); } } 并且使用window.onload = init。
替换init()的调用答案 2 :(得分:0)
既然你说你是javascript的新手,我相信问题可能是你运行代码的浏览器可能不支持画布。