我想在画布上为我的脚本创建一个背景,使图像下降并在屏幕上向下旋转。那么有人能够向我解释如何旋转图像然后使用<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)以圆形形状移动,我希望它保持在现场旋转的同一个地方。我将如何解决此问题!
答案 0 :(得分:3)
保存context
,对其进行转换,旋转,绘画,还原。
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var ctx = document.getElementById('cvs').getContext('2d'),
RAD = Math.PI/180,
width = window.innerWidth,
height = window.innerHeight,
fallingIconsAll = [],
FallingIcon = function() {
this.x = rand(0, width);
this.y = rand(0, height);
this.h = 32;
this.w = 32;
this.angle = rand(0, 360);
this.speed = rand(1, 4);
this.IMG = new Image();
this.IMG.src = 'http://stackoverflow.com/favicon.ico';
return this;
};
ctx.canvas.width = width,
ctx.canvas.height = height,
FallingIcon.prototype.move = function () {
// Manipulate Icon properties
if( this.y > height + this.h ) { // (if has dropped)
this.y = -this.h; // restart from top
this.x = rand(0, width); // new X position
this.speed = rand(1, 4); // new random speed
}
this.y += this.speed;
this.angle += this.speed % 360;
// Manipulate context
ctx.save(); // save context
ctx.translate(this.x, this.y); // move to point
ctx.rotate(this.angle * RAD); // rotate around that point
ctx.drawImage(this.IMG, -(this.IMG.width/2), -(this.IMG.height/2));
ctx.restore(); // restore to initial coordinates
};
// Create falling Icons
for (var i = 0; i < 20; i++) {
fallingIconsAll.push(new FallingIcon());
}
// Setup Canvas
ctx.canvas.width = width;
ctx.canvas.height = height;
// Animation loop
(function loop () {
ctx.clearRect(0, 0, width, height);
fallingIconsAll.forEach(function (Icon) {
Icon.move();
});
requestAnimationFrame(loop);
}());
&#13;
body{margin:0;} canvas{display:block;}
&#13;
<canvas id="cvs"></canvas>
&#13;