小编The*_*ate的帖子

从方向向量获取角度?

我有这个简单的函数来设置矢量的角度.它有效地获取向量的当前幅度(长度),计算角度并将角度从弧度转换为度.然后我将角度应用于X和Y,最后将矢量乘以它的原始幅度.

this.setAngle = function(degree){
    var l = this.length();  //magnitude of vector
    var angle = degree*Math.PI/180; //degress converted to radians
    this.x=Math.cos(angle);
    this.y=Math.sin(angle);
    this.multiply(l);  //original magnitude
    return;
}
Run Code Online (Sandbox Code Playgroud)

但是我不确定如何从Vector获得(获得)角度.以下是我的尝试:

this.getAngle = function(){
    var angle = Math.atan(this.y/this.x);   //radians
    var degrees = angle/(180*Math.PI);  //degrees
    return Math.floor(degrees); //round number, avoid decimal fragments
}
Run Code Online (Sandbox Code Playgroud)

此尝试不会返回除0或-1之外的任何值.

有什么建议?

编辑:

正确的方法:

this.getAngle = function(){
    var angle = Math.atan2(this.y, this.x);
    var degrees = 180*angle/Math.PI;
    return (360+Math.round(degrees))%360;
}
Run Code Online (Sandbox Code Playgroud)

javascript vector angle direction

4
推荐指数
1
解决办法
6483
查看次数

更改Image()对象尺寸(宽度和高度)

我试图调整图像的尺寸,同时保持它的纵横比.这似乎是一个非常简单的任务,但我找不到任何地方的相关答案..(与JavaScript的Image()对象有关).我可能错过了一些非常明显的东西.以下是我想要实现的目标:

var img = new window.Image();
img.src = imageDataUrl;
img.onload = function(){
    if (img.width > 200){
        img.width = 200;
        img.height = (img.height*img.width)/img.width;
    }
    if (img.height > 200){
        img.height = 200;
        img.width = (img.width*img.height)/img.height;
    }
};
Run Code Online (Sandbox Code Playgroud)

这是按比例调整图像大小,然后像这样绘制到画布上:.context.drawImage(img,0,0,canvas.width,canvas.height);但是看起来我不能直接改变Image()尺寸,那么它是如何完成的呢?谢谢.

编辑:我没有使用交叉乘法正确解决图像比例.@markE提供了一种获得正确比率的简洁方法.以下是我的新(工作)实现:

var scale = Math.min((200/img.width),(200/img.height));
img.width = img.width*scale;
img.height = img.height*scale;
clearCanvas(); //clear canvas
context.drawImage(img,0,0,img.width,img.height);
Run Code Online (Sandbox Code Playgroud)

javascript canvas aspect-ratio

3
推荐指数
2
解决办法
1万
查看次数

标签 统计

javascript ×2

angle ×1

aspect-ratio ×1

canvas ×1

direction ×1

vector ×1