수색…


타원

여기에 이미지 설명을 입력하십시오.

주 : 브라우저는 내장 된 context.ellipse 드로잉 명령을 추가하는 중입니다 context.ellipse 그러나이 명령은 보편적으로 채택되지 않습니다 (특히 IE에는 포함되지 않음). 아래의 방법은 모든 브라우저에서 작동합니다.

원하는 좌상단 좌표를 사용하여 타원을 그립니다.

// draws an ellipse based on x,y being top-left coordinate
function drawEllipse(x,y,width,height){
    var PI2=Math.PI*2;
    var ratio=height/width;
    var radius=Math.max(width,height)/2;
    var increment = 1 / radius;
    var cx=x+width/2;
    var cy=y+height/2;
    
    ctx.beginPath();
    var x = cx + radius * Math.cos(0);
    var y = cy - ratio * radius * Math.sin(0);
    ctx.lineTo(x,y);

    for(var radians=increment; radians<PI2; radians+=increment){ 
        var x = cx + radius * Math.cos(radians);
        var y = cy - ratio * radius * Math.sin(radians);
        ctx.lineTo(x,y);
     }

    ctx.closePath();
    ctx.stroke();
}

원하는 중심점 좌표를 기준으로 타원을 그립니다.

// draws an ellipse based on cx,cy being ellipse's centerpoint coordinate
function drawEllipse2(cx,cy,width,height){
    var PI2=Math.PI*2;
    var ratio=height/width;
    var radius=Math.max(width,height)/2;
    var increment = 1 / radius;

    ctx.beginPath();
    var x = cx + radius * Math.cos(0);
    var y = cy - ratio * radius * Math.sin(0);
    ctx.lineTo(x,y);

    for(var radians=increment; radians<PI2; radians+=increment){ 
        var x = cx + radius * Math.cos(radians);
        var y = cy - ratio * radius * Math.sin(radians);
        ctx.lineTo(x,y);
     }

    ctx.closePath();
    ctx.stroke();
}

흐림없는 선

Canvas가 선을 그릴 때 앤티 앨리어싱이 자동으로 추가되어 시각적으로 "들쭉날쭉 함"을 치료합니다. 결과는 덜 들쭉날쭉하지만 더 흐릿한 선입니다.

이 함수는 Bresenham 's _line 알고리즘을 사용하여 앤티 앨리어싱없이 2 포인트 사이에 선을 그립니다. 결과는 지그재그가없는 선명한 선입니다.

중요 : 이 픽셀 별 방법은 context.lineTo 보다 훨씬 느린 그리기 방법입니다.

여기에 이미지 설명을 입력하십시오.

// Usage:
bresenhamLine(50,50,250,250);

// x,y line start
// xx,yy line end
// the pixel at line start and line end are drawn
function bresenhamLine(x, y, xx, yy){
    var oldFill = ctx.fillStyle;  // save old fill style
    ctx.fillStyle = ctx.strokeStyle; // move stroke style to fill
    xx = Math.floor(xx);
    yy = Math.floor(yy);
    x = Math.floor(x);
    y = Math.floor(y);
    // BRENSENHAM 
    var dx =  Math.abs(xx-x); 
    var sx = x < xx ? 1 : -1;
    var dy = -Math.abs(yy-y);
    var sy = y<yy ? 1 : -1; 
    var err = dx+dy;
    var errC; // error value
    var end = false;
    var x1 = x;
    var y1 = y;

    while(!end){
       ctx.fillRect(x1, y1, 1, 1); // draw each pixel as a rect
        if (x1 === xx && y1 === yy) {
            end = true;
        }else{
            errC = 2*err;
            if (errC >= dy) { 
                err += dy; 
                x1 += sx; 
            }
            if (errC <= dx) { 
                err += dx; 
                y1 += sy; 
            } 
        }
    }
    ctx.fillStyle = oldFill; // restore old fill style
}


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow