gpt4 book ai didi

javascript - 我如何使这个动画工作?

转载 作者:太空宇宙 更新时间:2023-11-04 15:38:22 26 4
gpt4 key购买 nike

我想要一个水平移动的矩形。但是,矩形没有动画。我该如何解决这个问题?

<script type="text/javascript">
var interval = 10;
var x=0;
var y=0;
var rect = null;
var context ;
var canvas;

function Rectangle(x, y, width, height, borderWidth) {
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.borderWidth = borderWidth;
}

function DrawRects(){
myRectangle = new Rectangle (250,70,100,50, 5);

context.rect(myRectangle.x,myRectangle.y,myRectangle.width,myRectangle.height)
context.fillStyle="#8ED6FF";
context.fill();
context.lineWidth=myRectangle.borderWidth;
context.strokeStyle="black";
context.stroke();
}

function updateStageObjects() {
var amplitude = 150;
var centerX = 240;
var nextX = myRectangle.x+ 10;

myRectangle.x = nextX;
}

function clearCanvas() {
context.clearRect(0,0,canvas.width, canvas.height);
}

function DrawRect(){
alert("Test1");
setTimeout(CheckCanvas,10);

//clearCanvas();

updateStageObjects();

DrawRects();
alert("Test2");
}

function CheckCanvas(){
return !!(document.createElement('canvas').getContext);
}

function CheckSound(){
return !!(document.createElement('sound').canPlayType)
}

function CheckVideo(){
return !!(document.createElement('video').canPlayType)
}

function Checkstorage(){
return !!(window.localStorage)
}

function CheckVideo(){
return !!(document.createElement('video').canPlayType)
}

function DrawCanvas(){
if (CheckCanvas()){
canvas = document.getElementById('Canvas');
context =canvas.getContext('2d');

$('#Result').text('Canvas supported...');
$('#Result').text($('#Result').text()+'Sound supported...'+CheckSound());
$('#Result').text($('#Result').text()+'Video supported...'+CheckVideo());
$('#Result').text($('#Result').text()+'Storage supported...'+Checkstorage());

DrawRects();
setInterval(DrawRect(), 10);
}
}
</script>

HTML:

<canvas id="Canvas" width="800px" height="800px" onclick="DrawCanvas()"> Nor supported</canvas>

最佳答案

你需要做的

setInterval(DrawRect, 10);

使用 DrawRect() 将调用该函数一次,然后尝试调用该函数的结果,作为一个函数(它不是)每 10毫秒。

关于javascript - 我如何使这个动画工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6478836/

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