【问题标题】:Compare points of a circle in canvas with a drawing made in canvas by the user将画布中的圆点与用户在画布中绘制的绘图进行比较
【发布时间】:2018-12-20 17:21:33
【问题描述】:

我必须编写一个从画布中的圆圈开始的代码,用户可以在其上绘制并将正确圆圈的点与用户在顶部绘制的点进行比较。从而推断出用户失败或成功的百分比。

这就是我保持正确圆坐标的方式。

var centerX=200;
var centerY=200;
var radius=70;

// array save circlePoints
var points=[];

for(var degree=0;degree<360;degree++){
    var radians = degree * Math.PI/180;
    var x = centerX + radius * Math.cos(radians);
    var y = centerY + radius * Math.sin(radians);
    points.push({x:x,y:y});
}

这就是用户在画布上绘制的方式,我保存了这个坐标:

function findxy(res, e) {
    if (res == 'down') {
        prevX = currX;
        prevY = currY;
        currX = e.clientX - canvas.offsetLeft;
        currY = e.clientY - canvas.offsetTop;

        arrayCoordenadas.push({currX:currX,currY:currY});

        flag = true;
        dot_flag = true;
        if (dot_flag) {
            ctx.beginPath();
            ctx.fillStyle = x;
            ctx.fillRect(currX, currY, 2, 2);
            ctx.closePath();
            dot_flag = false;
        }
    }
    if (res == 'up' || res == "out") {
        flag = false;
    }
    if (res == 'move') {
        if (flag) {
            prevX = currX;
            prevY = currY;
            currX = e.clientX - canvas.offsetLeft;
            currY = e.clientY - canvas.offsetTop;
            arrayCoordenadas.push({currX:currX,currY:currY});
            draw();
        }
    }
}

我不知道我绘制时保存坐标的方式是否正确,也不知道如何比较两个数组。

【问题讨论】:

    标签: javascript arrays canvas coordinates geometry


    【解决方案1】:

    我建议查找坐标的更简单方法是将初始圆值存储在一个对象中,其中x 的每个值都有一个与之关联的y 值数组。此处的示例显示了如何检查每个用户点以查看它是否与圆上的点匹配。

    var centerX=200;
    var centerY=200;
    var radius=70;
    
    // array save circlePoints
      //set to object instead, for each X value store an array of Y values that correspond.
      //this makes checking a user point easier
    var points = {};
    
    for(var degree=0;degree<360;degree++){
        var radians = degree * Math.PI/180;
        var x = centerX + radius * Math.cos(radians);
        var y = centerY + radius * Math.sin(radians);
        
        if(!points[x]) points[x] = [] //if the array for point x doesn't exist, create it
        points[x].push(y) //push the y value into the array for the x value
    }
    
    
    function isPointOnCircle(x,y){
      return !!points[x] && points[x].indexOf(y) > -1
    }
    
    
    var userPoints = [
      [270,200],
      [130,50],
      [200,270],
      [100,200]
    ]
    
    userPoints.forEach(point => {
      console.log(isPointOnCircle(...point))
    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      相关资源
      最近更新 更多