gpt4 book ai didi

javascript - Raphael JS图像动画表现

转载 作者:行者123 更新时间:2023-12-01 03:31:20 24 4
gpt4 key购买 nike

我正在尝试使用 Raphael JS 创建图像动画。

我想要蜜蜂在页面上随机移动的效果,我有一个工作示例,但它有点“紧张”,我在控制台中收到此警告:

“资源解释为图像但以 MIME 类型文本/html 传输”

我不确定警告是否导致了“紧张”运动,或者它只是我使用数学处理它的方式。

如果有人有更好的方法来创建效果或改进,请告诉我。

我有在线演示here

这是我的 javascript 代码:

function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

function BEE(x, y, scale) {
this.x = x;
this.y = y;
this.s = scale;
this.paper = Raphael("head", 915, 250);

this.draw = function() {
this.paper.clear();
this.paper.image("bee.png", this.x, this.y, 159*this.s, 217*this.s);
}

this.update = function() {
var deg = random(-25, 25);

var newX = Math.cos(Raphael.rad(deg)) * 2;
var newY = Math.sin(Raphael.rad(deg)) * 2;

this.x += newX;
this.y += newY;

if( this.x > 915) {
this.x = 0;
}
if( this.y > 250 || this.y < 0 ) {
this.y = 125;
}
}
}

$(document).ready(function() {

var bee = new BEE(100, 150, 0.4);
var timer = setInterval(function(){
bee.draw();
bee.update();
}, 15);
}

最佳答案

您没有使用 Raphael 的最佳功能,即仅在您创建的对象上设置属性的能力,就像 DOM 一样。您正在重新实例化蜜蜂并在每一步都清除纸张。这就是使用 canvas 标签的方式,它非常乏味且容易出错,让浏览器担心要重新绘制什么。

做你正在做的事情的更好方法是以下

/**
* I don't like closure object orientation, but if you're
* going to use it, use it all the way
* (instead of using this.x and this.y for private variables)
*/
function Bee(paper, x, y, scale)
{

// The Raphael img object for the bee)
var img = paper.image("bee.png", x, y, 159 * scale, 217 * scale);

var timerId = null;

// Allows access to 'this' within closures
var me = this;

this.draw = function() {
img.attr({x: x, y: y});
}

this.update = function() {
var deg = random(-25, 25);

var newX = Math.cos(Raphael.rad(deg)) * 2;
var newY = Math.sin(Raphael.rad(deg)) * 2;

x += newX;
y += newY;

if( x > 915) {
x = 0;
}
if( y > 250 || y < 0 ) {
y = 125;
}
}

this.fly = function() {
timerId = setInterval({
me.update();
me.draw();
}, 15);
}

this.stop = function() {
clearInterval(timerId);
timerId = null;
}

function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}

$(document).ready(function() {
var paper = Raphael("head", 915, 250);
var bees = [ new Bee(paper, 100, 150, 0.4), new Bee(paper, 50, 10, 0.2) ];
bees[0].fly();
bees[1].fly();
$(document).click(
bees[0].stop();
bees[1].stop();
);

}

关于javascript - Raphael JS图像动画表现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4515152/

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