HTML5 画布:围绕画布边缘绘制形状
HTML5 Canvas: Drawing shapes around edges of the canvas
我正在创建一个基本的游戏,在画布上的随机位置绘制正方形,但有时形状会被切断,因为它超出了画布的边界。谁能解释一下我如何让正方形画在画布的另一边(类似于在小行星上的做法)?我想出的搜索没有帮助。任何帮助,不胜感激。
好的,
我想我已经解决了这个问题。基本上,此代码仅在画布内绘制正方形,如果它离开画布,它会检查它离开的边界并更新位置。需要循环变量,否则正方形将始终离开画布。
var canvas = document.getElementById('bg');
var ctx = canvas.getContext('2d');
var squares = [];
squares[squares.length] = new Square(200, 200, 20, 'red', 0.785398164);
function Square(x, y, size, colour, angle)
{
this.x = x;
this.y = y;
this.size = size;
this.colour = colour;
this.speed = 5;
this.angle = angle;
this.looped = false;
}
Square.prototype.update = function()
{
this.x += (Math.cos(this.angle) * this.speed);
this.y += (Math.sin(this.angle) * this.speed);
if (this.x < canvas.width && this.x + this.size > 0 &&
this.y < canvas.height && this.y + this.size > 0)
{
this.draw();
this.looped = false;
}
else
{
if (this.x > canvas.width && !this.looped)
{
this.x = -this.size;
}
if (this.x + this.size < 0 && !this.looped)
{
this.x = this.size + canvas.width;
}
if (this.y > canvas.height && !this.looped)
{
this.y = -this.size;
}
if (this.y + this.size < 0 && !this.looped)
{
this.y = this.size + canvas.height;
}
this.looped = true;
}
}
Square.prototype.draw = function()
{
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.size, this.size);
}
function gameLoop()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < squares.length; i++)
{
squares[i].update();
}
requestAnimationFrame(gameLoop);
}
gameLoop();
(function()
{
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x)
{
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element)
{
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function()
{
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id)
{
clearTimeout(id);
};
}());
我会做一个JSFiddle,但requestAnimationFrame不能很好地使用它。
相关文章:
- D3在一个调用中绘制不同的SVG形状,没有可见性
- 有没有一个javascript图形绘制库可以进行气球树布局
- 使用相同的数据集绘制各种符号
- 下拉菜单在菜单按钮的边缘闪闪发光
- 使用onclick绘制SVG路径
- 在谷歌地图上绘制位置数据库
- 用chart.js绘制条形图
- “可绘制地图”设置地图选项“纬度-经度”
- 多维数据集网格未在指定的分区中绘制
- 使用谷歌图表在x轴上绘制日期
- 使用fabric.js从矩形区域获取对象,并将该区域绘制到画布上
- 如何在React Native中绘制图形
- 如何在图片和边缘之间居中设置标签
- 画布中绘制的矩形区域的弹出工具提示
- 库存图表-添加偏移以避免在边缘绘制点
- 如何在Sigma.js Graph上绘制边缘标签
- Html5画布绘制:快速移动鼠标取消线之前,它击中画布的边缘
- JavaScript HTML5-Canvas - 使用 SetInterval 绘制弧会导致锯齿状边缘
- HTML5 画布:围绕画布边缘绘制形状
- 在X3DOM中绘制边缘