让小球在浏览器可视区域内拖拽自如

	var obj  = document.getElementsByClassName('qiu')[0];
			obj.addEventListener('mousedown',function(event){
			    //获取浏览器窗口宽度 和 高度
				let clientW = window.innerWidth;
				let clientH = window.innerHeight;
				//获取当前元素的宽高
				let elW = obj.offsetWidth;
				let elH = obj.offsetHeight;
				
				//算出鼠标相对元素的位置
				let pointX = event.clientX - obj.offsetLeft;//鼠标位置X减去元素距离左边距离(鼠标到元素左边的距离)
				let pointY = event.clientY - obj.offsetTop;//鼠标位置Y减去距离顶部距离(鼠标到元素顶部的高度)
				document.onmousemove = (e)=>{
				    //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
				    let left = e.clientX - pointX;
				    let top = e.clientY - pointY;
					left = left<0 ? 0 : left;
					top = top<0 ? 0 : top;
					left = left > (clientW - elW) ? (clientW - elW)  :left 
					top = top > (clientH - elH) ? (clientH - elH)  :top
				    //移动当前元素
				    obj.style.left = left + 'px';
				    obj.style.top = top + 'px';
				};
				document.onmouseup = (e) => {
				    document.onmousemove = null;
				    document.onmouseup = null;
				};
			})
			  


好的,这是一个简单的动画效果,可以使用 Python 的 Pygame 库来实现。以下是一个示例代码,可以在 Pygame 环境下运行: ```python import pygame import random # 初始化 Pygame pygame.init() # 窗口尺寸 WIDTH, HEIGHT = 640, 480 # 创建窗口 screen = pygame.display.set_mode((WIDTH, HEIGHT)) # 矩形位置和大小 rect_x, rect_y = 200, 150 rect_width, rect_height = 240, 180 # 小球半径和速度 ball_radius = 10 ball_speed_x, ball_speed_y = 5, 5 # 小球位置 ball_x = random.randint(rect_x + ball_radius, rect_x + rect_width - ball_radius) ball_y = random.randint(rect_y + ball_radius, rect_y + rect_height - ball_radius) # 游戏循环 while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: # 关闭窗口 pygame.quit() exit() # 移动小球 ball_x += ball_speed_x ball_y += ball_speed_y # 检测小球是否碰到矩形边缘 if ball_x - ball_radius < rect_x or ball_x + ball_radius > rect_x + rect_width: ball_speed_x = -ball_speed_x if ball_y - ball_radius < rect_y or ball_y + ball_radius > rect_y + rect_height: ball_speed_y = -ball_speed_y # 填充窗口背景色 screen.fill((255, 255, 255)) # 绘制矩形和小球 pygame.draw.rect(screen, (0, 0, 0), (rect_x, rect_y, rect_width, rect_height), 2) pygame.draw.circle(screen, (255, 0, 0), (ball_x, ball_y), ball_radius) # 更新屏幕 pygame.display.update() # 控制帧率 pygame.time.Clock().tick(60) ``` 这段代码创建了一个大小为 640x480 的窗口,内部有一个矩形和一个小球小球在矩形内随机运动,碰到边缘时会反弹。每秒钟更新屏幕 60 次,控制帧率为 60 帧。你可以根据需要修改代码中的参数和细节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值