画布对图像旋转进行动画处理
Canvas animate images rotation
我想在画布上为我的脚本创建一个背景,使图像在屏幕上下落和旋转。那么有人能够向我解释我如何旋转图像,然后使用 <canvas>
元素将其绘制到屏幕上。我有以下代码:
Equations.prototype.Draw = function() {
//increases the rotational value every loop
this.rotate = (this.rotate + 1) % 360;
//rotates the canvas
ctx.rotate(this.rotate*Math.PI/180);
//draw the image using current canvas rotation
ctx.drawImage(this.img,this.x,this.y);
//restore canvas to its previous state
ctx.rotate(-this.rotate*Math.PI/180);
};
我尝试了这个,发现图像旋转,但也在屏幕上以圆形围绕点 (0,0) 移动,我希望它保持在原地旋转的同一个地方。我将如何解决这个问题,谢谢!
保存context
,变换它,旋转它,绘画,恢复它。
const rand = (m, M) => Math.random() * (M - m) + m,
PI = Math.PI,
TAU = PI * 2,
width = window.innerWidth,
height = window.innerHeight,
ctx = document.getElementById('cvs').getContext('2d'),
items = [],
Item = function() {
this.h = 32;
this.w = 32;
this.IMG = new Image();
this.IMG.src = 'http://stackoverflow.com/favicon.ico';
this.start();
return this;
};
Item.prototype.start = function() {
this.x = rand(0, width - this.w / 2);
this.y = rand(0, height);
this.angle = rand(0, TAU);
this.speed = rand(0.1, 0.5);
}
Item.prototype.move = function() {
// Manipulate properties
if (this.y > height + this.h) { // if is below bottom
this.start();
this.y = -this.h; // restart from top
}
this.y += this.speed / 0.1;
this.angle += this.speed;
this.angle %= TAU;
// Manipulate context
ctx.save(); // save context
ctx.translate(this.x, this.y); // move to point
ctx.rotate(this.angle); // rotate around that point
ctx.drawImage(this.IMG, -this.w/2, -this.h/2);
ctx.restore(); // restore to initial coordinates
};
// Setup canvas
ctx.canvas.width = width;
ctx.canvas.height = height;
// Create falling Icons
for (var i = 0; i < 100; i++) items.push(new Item());
// Animation loop
(function loop() {
ctx.clearRect(0, 0, width, height);
items.forEach(Item => Item.move());
requestAnimationFrame(loop);
}());
body {margin: 0;}
canvas {display: block;}
<canvas id="cvs"></canvas>
相关文章:
- 使用不同的超时对数组中的每个项目进行角度动画处理
- 图表.js 2,从右到左(不是自上而下)进行动画处理
- 使用 JavaScript 对 HTML5 进度条进行动画处理
- 使用 JQuery 对 Spin SVG 元素进行动画处理
- 使用 GSAP 对模糊滤镜进行动画处理
- 使用 jQuery 对窗口进行动画处理
- 如何使用jQuery对固定元素的位置进行动画处理
- jQuery 动画处理最大宽度溢出问题
- 悬停不起作用时对不透明度更改进行动画处理
- 在两个值之间插值或“补间”(但不进行动画处理)
- 尝试在画布中对形状进行动画处理时,它会显示,但不移动
- 如何在不分隔跨度字母的情况下对文本进行动画处理
- 对链接的 svg 进行动画处理不起作用;内联时工作正常
- 防止对某些事件进行进一步的动画处理
- Snap.svg:在动画中使用相同的种类对多个零件进行动画处理
- 如何使用if语句jquery对数字进行动画处理
- 按随机顺序对元素进行动画处理
- 元素在使用 jQuery 对相对包装宽度进行动画处理时消失
- brush.event 在对画笔事件进行动画处理时会做什么
- 使用ScrollMagic按顺序对多个场景进行动画处理