本文主要是介绍【实例】小球运动,像皮筋那样,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在线演示
点击框中任意位置,之后拖动鼠标确定运行的方向和力度之后松开鼠标小球运动
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style type="text/css">#canvas {border: thin solid black;}</style></head><body><canvas id="canvas" width="800" height="600"></canvas></body><script type="text/javascript">var canvas = document.getElementById("canvas");var context = canvas.getContext("2d");//小球对象 var ball = {x: 100,y: 400,r: 50,stepX: 8,stepY: 10};//判断是否在鼠标按下var dragging = false;//按下坐标var startLoc = null;//松开鼠标时的坐标var endLoc = null;//用于停止小球运动的“引用”var moveKey = null;//获取以窗口为参照的坐标function windowToCanvas(x, y) {var bbox = canvas.getBoundingClientRect();return {x: x - bbox.left * (canvas.width / bbox.width),y: y - bbox.top * (canvas.height / bbox.height)};}//清空当前画布function clearAll() {context.clearRect(0, 0, canvas.width, canvas.height);}//绘制新的小球function draw() {//先判断下一步的位置是否到了canvas的边界if (ball.x + ball.stepX + ball.r > canvas.width) {//当球的下一步运动到canvas的右边界的时候//改变X轴的运行方向ball.stepX = -ball.stepX;//真实的触碰到canvas右边界,而不是直接转向ball.x = canvas.width - ball.r;} else if (ball.x + ball.stepX - ball.r < 0) {//当球的下一帧触碰到canvas的左边界的时候//改变X轴的运动方向ball.stepX = -ball.stepX;//也是真实的触碰到X轴ball.x = 0 + ball.r;} else {//不会触碰到边界的情况,直接运动就好ball.x += ball.stepX;}//Y轴方向上的与X轴类似if (ball.y + ball.stepY + ball.r > canvas.height) {ball.stepY = -ball.stepY;ball.y = canvas.height - ball.r;} else if (ball.y + ball.stepY - ball.r < 0) {ball.stepY = -ball.stepY;ball.y = 0 + ball.r;} else {ball.y += ball.stepY;}drawArc(ball);}//画圆function drawArc(ball) {context.save();context.beginPath();context.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);context.stroke();context.closePath();}//计算速度function velocity() {ball.stepX = (endLoc.x - startLoc.x) / 10;ball.stepY = (endLoc.y - startLoc.y) / 10;}//运动function animate() {//先清除clearAll();//再绘制draw();//然后一直这样下去moveKey = requestAnimationFrame(animate);}canvas.onmousedown = function(e) {//进入鼠标按下状态dragging = true;//停止当前运动if (moveKey != null && moveKey != undefined) {cancelAnimationFrame(moveKey);}//获取鼠标按下坐标startLoc = windowToCanvas(e.clientX, e.clientY);//清除原来的数据clearAll();//绘制一个圆,在鼠标按下点的地方,圆的半径我这里默认弄成了50//当50半径的圆超出右边线时,直接把半径设置为圆与边线相切if (startLoc.x + 50 > canvas.width) {ball.r = canvas.width - startLoc.x;}//当50半径的圆超出左边线时if (startLoc.x < 50) {ball.r = startLoc.x;}if (startLoc.y + 50 > canvas.height) {ball.r = canvas.height - startLoc.y;}if (startLoc.y < 50) {ball.r = startLoc.y;}ball.x = startLoc.x;ball.y = startLoc.y;drawArc(ball);};canvas.onmousemove = function(e) {//必须得是鼠标按下状态if (dragging) {var loc = windowToCanvas(e.clientX, e.clientY);clearAll();drawArc(ball);context.save();context.beginPath();context.moveTo(ball.x, ball.y);context.lineTo(loc.x, loc.y);context.stroke();context.closePath();context.restore();}}canvas.onmouseup = function(e) {dragging = false;endLoc = windowToCanvas(e.clientX, e.clientY);//计算速度velocity();animate();};</script></html>
这篇关于【实例】小球运动,像皮筋那样的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!