繁体   English   中英

canvas动画javascript函数和全局变量

[英]canvas animation javascript functions and global variables

请,有人可以帮我! 我是javascript新手。
我想使用javascript制作画布动画。 但是我有以下错误

SCRIPT5007:无法获取属性'getContext'的值:对象为null或未定义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>

发生这种情况是因为您在创建画布之前执行了脚本。

创建画布元素FIRST,然后嵌入javascript。

IE:canvasCircle未定义,因为您无法通过尚不存在的ID获得元素!

我找到了答案: init()应该是

function init() {
    s_canvas = document.getElementById("canvas_square");
    // Check if the canvas is supported and if the getContext is available
    if (s_canvas && s_canvas.getContext) {
        s_context = s_canvas.getContext("2d");
        return setInterval(draw, 10);
    }
    else {
        alert("Canvas is not supported!");
    }
}

init()的调用被window.onload=init替换。

既然您说过您是javascript的新手,所以我认为问题可能在于您正在运行代码的浏览器可能不支持canvas。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM