canvas动画javascript函数和全局变量 [英] canvas animation javascript functions and global variables

查看:370
本文介绍了canvas动画javascript函数和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人帮助我!我是javascript的新人。
我想使用javascript制作画布动画。但是我有以下错误
SCRIPT5007:无法获取属性getContext的值:对象为null或未定义
drawing_script.js,第31行字符5
下面是代码。
Javascript:

Please may someone help me! I am new in javascript. I want to make canvas animation using javascript. But I have the following error SCRIPT5007: Unable to get value of the property 'getContext': object is null or undefined drawing_script.js, line 31 character 5 Here is the code. 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>


推荐答案

创建canvas元素FIRST然后嵌入javascript。

Create the canvas element FIRST then embed the javascript.

IE:canvasCircle未定义,因为不能通过ID仍然不存在的元素!

IE: canvasCircle is undefined because you can't get an element by ID that does not exist yet!

这篇关于canvas动画javascript函数和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆