javascript - 我需要一些数学帮助,将多个图像旋转到 JS 中的一个点

标签 javascript html math rotation html5-canvas

这是我的完整信息 Js Fiddle progress

function drawPetals(num){
for(var i=0;i<num;i++){
    var p = Math.random()
    var x = bud.x + (bud.size+50) * Math.cos(2 * Math.PI * p);
    var y = bud.y + (bud.size+50) * Math.sin(2 * Math.PI * p);
    petals[i] = new Petal();
    petals[i].draw(x,y, Math.atan2(bud.x*x,bud.y*y) //Math.atan needs to change);
}

}

我尝试了 Math.atan2() 但我什至不知道它的作用和工作原理 petals[i].draw() 需要 3 个参数 x,y 和旋转,旋转是我需要填写的..,无论我在它周围随机放置多少花瓣,它都需要指向该点。

我基本上想要花瓣面向红点,形成一朵花。 我的小程序的目标是拥有随机数量的花瓣,点击按钮就会拿走一个花瓣,就像“他爱我,他不爱我”——女孩会做的事情。

我的数学不够好,无法弄清楚这一点,但不要完全完成该程序,我这样做是为了学习目的,因为我(很明显)是一个初学者。 :)

请随意教我背后的数学,我喜欢变得更聪明。

预先感谢您的智慧;)

最佳答案

编译代码时出现一些问题。检查 javascript 控制台以查找任何 javascript 错误。我已向 bud 对象添加了一个 init 方法。一旦编译完成,您就离成功不远了。

使用one.draw(bud.x,bud.y,120);绘制和 ctx.drawImage(image, -(w/2), -h,w,h);将事物放置在正确的位置。

完整的工作示例是:

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;

var TO_RADIANS = Math.PI/180; 

var bud = {
    size:15,
    init : function() {
        this.x = (canvas.width-this.size)/2;
        this.y = (canvas.height-this.size)/2;
    },
    draw: function(){
        console.log("bud,draw",this.x,this.y,this.size);
        drawCircle(this.x,this.y,this.size);
    }
}

function Petal(){
    this.w = bud.size*3.5;
    this.h = bud.size*3.5;
    this.img = new Image();
    this.img.src = "http://i.imgur.com/BMeZIvV.jpg";
    this.draw = function(middleX,middleY,angle){
      drawRotatedImage(this.img,middleX,middleY,this.w,this.h,angle);
    }
}

bud.init();
var one = new Petal();
one.draw(bud.x,bud.y,120);
one.draw(bud.x,bud.y,-120);
one.draw(bud.x,bud.y,0);
bud.draw();

function drawCircle(x,y,size){
    ctx.fillStyle = "green";
    ctx.beginPath();
    ctx.arc(x,y,size,0,2*Math.PI);
    ctx.fill();
}

function drawRotatedImage(image, x, y, w, h, angle) { 
 console.log("drawRotatedImage",x,y,w,h,angle);
    // save the current co-ordinate system 
    // before we screw with it
    ctx.save(); 

    // move to the middle of where we want to draw our image
    ctx.translate(x, y);

    // rotate around that point, converting our 
    // angle from degrees to radians 
    ctx.rotate(angle * TO_RADIANS);

    // draw it up and to the left by half the width
    // and height of the image 
    ctx.drawImage(image, -(w/2), -h,w,h);

    // and restore the co-ords to how they were when we began
    ctx.restore(); 
}

关于javascript - 我需要一些数学帮助,将多个图像旋转到 JS 中的一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804062/

相关文章:

使用算法将未绑定(bind)值转换为绑定(bind)值?

javascript - Jquery 将下拉列表中的值添加到文本输入

javascript - 将模块注入(inject)另一个模块

java - 求两条曲线之间的面积(每条曲线由一组点组成)

javascript - 如果存在子菜单,如何将跨度 append 到 <li>

javascript - Phonegap Android 写入 SD 卡

python - 在 NumPy 中旋转晶体

javascript - MSSQL Server 到 PHP 数组到 JSON 编码到 Highcharts

javascript - 为什么抛出异常后就不再认为发生了?

javascript - 限制特定div中的jquery函数