我正在尝试使用Raphael JS创建一个图像动画。
我想要蜜蜂在页面上随机移动的效果,我有一个有效的例子,但它有点“紧张”,我在控制台收到这个警告:
“资源被解释为图像但使用MIME类型text / 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);
}
答案 0 :(得分:7)
您没有使用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();
);
}