gpt4 book ai didi

javascript - canvas动画javascript函数和全局变量

转载 作者:行者123 更新时间:2023-11-28 16:31:40 25 4
gpt4 key购买 nike

请有人帮助我!我是 JavaScript 新手。
我想使用 javascript 制作 Canvas 动画。但我有以下错误

SCRIPT5007: Unable to get value of the property 'getContext': object is null or undefined drawing_script.js, line 31 character 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>

最佳答案

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

首先创建 Canvas 元素,然后嵌入 JavaScript。

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

关于javascript - canvas动画javascript函数和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5679355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com