我有一个想法,我想实现屏幕上跳动着各种图片的位置,学习者必须识别出哪张是正确的图片。
我用Google搜索了javascript images bouncing,这是第一个结果,虽然可以使用,但使用的是Canvas:
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 23;
var size_y = 22;
var canvas_size_x = 480;
var canvas_size_y = 320;
var anim_img = null;
function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() { setInterval('myAnimation()', 10); }
anim_img.src = 'https://pbs.twimg.com/profile_images/3352183391/a16302aab7bd8742ad3e39a75454008a_normal.jpeg';
}
function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
draw()
<canvas id="canvas" width="480" height="320" style="border:solid 1px;"></canvas>
我真的很想让它成为一个智能手机应用程序,所以我的想法是只使用dom并询问screen.width和screen.height。
问:有没有办法在不使用画布的情况下使html页面周围的超链接图像反弹?
答案 0 :(得分:2)
您可以在图片元素上使用绝对位置,只需更新其顶部/左侧值即可:
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 23;
var size_y = 22;
var anim_img = null;
function draw() {
anim_img = new Image(size_x, size_y);
anim_img.onload = function() { setInterval('myAnimation()', 10); }
anim_img.src = 'https://pbs.twimg.com/profile_images/3352183391/a16302aab7bd8742ad3e39a75454008a_normal.jpeg';
anim_img.style.position = 'absolute';
document.body.append(anim_img);
}
function myAnimation() {
if (x_icon < 0 || x_icon > window.innerHeight - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > window.innerWidth - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
anim_img.style.top = x_icon + 'px';
anim_img.style.left = y_icon + 'px';
}
draw()