2017-09-21 6 views
-1

산악 그래프를 만들려고합니다. (라인 차트와 밑 부분은 음영 처리됩니다.) 그러나 내가 시도한 것에 상관없이 음영 처리 된 영역은 전체 영역을 덮지 않습니다. 내 차트는 열린 경로이므로 차트 선을 통과하는 영역의 결과가 채워집니다. 다음은 HTML Canvas : 선 그래프에서 영역을 색칠하는 방법은 무엇입니까?

enter image description here

내가 문제를 보여 W3School에 넣어 샘플 코드입니다.

나는 또한 같은 줄에 몇 가지 다른 질문을 보았지만 그것들을 따르더라도 같은 문제가 발생합니다.

var c = document.getElementById("myCanvas"); 
 
var ctx = c.getContext("2d"); 
 
ctx.beginPath(); 
 
ctx.moveTo(0,150); 
 
ctx.lineTo(100,70); 
 
ctx.lineTo(150,100); 
 
ctx.lineTo(200,140); 
 
ctx.lineTo(250,90); 
 
ctx.lineTo(300,110); 
 
ctx.fillStyle ="red"; 
 
ctx.fill(); 
 
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> 
 
Your browser does not support the HTML5 canvas tag.</canvas>

+0

캔버스의 아래쪽 구석에 단일 점이 없습니다. 'ctx.filStyle' 전에'ctx.lineTo (300,150);로 끝내십시오. – PHPglue

+0

자주 묻지 않는 질문입니다. – PHPglue

+0

@PHPglue, 귀하의 답변이 좋지 않았으며 위의 의견이 좋지 않다고 말씀 드려서 죄송합니다. 왜 ? 요구 사항을 수정하여 대답했기 때문입니다. 나는 5 줄을주고 밑에 지역을 채우라고했다. 왜 당신이 옆에서 다른 라인을 추가하겠습니까? 그것은 당신이 산 그래프를 알지 못한다고 알려줍니다. 대답하기 위해 원래의 요구 사항을 수정하기 전에 명확히 해달라고 요청할 수있었습니다. – TypeScripter

답변

0

, 다음 lineTo(lastX, canvasHeight); lineTo(firstX, canvasHeight);fill()를 호출하기 전에.

이렇게하면 채워진 영역이 항상 모든 하단 영역을 덮습니다.
대신의 캔버스 바닥에 만 최대 Y 값으로 채우려는 경우에, 당신은 당신의 점에서이 MAXY (아래 미리보기에서 주석 부분) 잡아 수 있습니다

const width = canvas.width; 
 
const height = canvas.height; 
 
const ctx = canvas.getContext('2d'); 
 
ctx.fillStyle = 'red'; 
 

 
function plotPoints() { 
 
    const pts = generatePoints(32); 
 
    // first plot the stroke 
 
    pts.forEach((pt) => ctx.lineTo(pt.x, pt.y)); 
 
    ctx.stroke(); 
 
    // now define the bottom of the filled area 
 
    const maxY = height; //Math.max.apply(null, pts.map(pt=>pt.y)); 
 
    // draw the missing parts 
 
    ctx.lineTo(pts[pts.length - 1].x, maxY); // bottom-right 
 
    ctx.lineTo(pts[0].x, maxY); // bottom-left 
 
    ctx.fill(); // will close the path for us 
 
} 
 
plotPoints(); 
 

 
function generatePoints(nbOfPoints) { 
 
    const pts = []; 
 
    for (let i = 0; i <= nbOfPoints; i++) { 
 
    pts.push({ 
 
     x: i * (width/nbOfPoints), 
 
     y: Math.random() * height 
 
    }); 
 
    } 
 
    return pts; 
 
}
canvas { 
 
    border: 1px solid lightgray; 
 
}
<canvas id="canvas"></canvas>

+0

훌륭해 내가 찾고 있던 .. 고마워. – TypeScripter

+0

안녕하세요. 카이도, 답변을 약간 수정 해 주시겠습니까? 나는 실수로 당신을 뽑았습니다. 그리고 대답이 수정되지 않으면 그것을 바꿀 수 없습니다. 고마워하고 미안해. – TypeScripter

-1

이 같은입니다 : 당신은 그냥 먼저 stroke()에 경로가

//<![CDATA[ 
 
/* external.js */ 
 
var doc, bod, E; // for use on other loads 
 
addEventListener('load', function(){ 
 
doc = document, bod = doc.body; 
 
E = function(id){ 
 
    return doc.getElementById(id); 
 
} 
 
var graph = E('graph'), ctx = graph.getContext('2d'); 
 
ctx.beginPath(); ctx.moveTo(0,150); ctx.lineTo(100,70); 
 
ctx.lineTo(150,100); ctx.lineTo(200,140); ctx.lineTo(250,90); 
 
ctx.lineTo(300,110); ctx.lineTo(300,110); ctx.lineTo(300,150); 
 
ctx.fillStyle = 'red'; ctx.fill(); ctx.stroke(); 
 
}); 
 
//]]>
/* external.css */ 
 
html,body{ 
 
    padding:0; margin:0; 
 
} 
 
.main{ 
 
    width:940px; padding:20px; margin:0 auto; 
 
} 
 
#graph{ 
 
    width:300px; height:150px; 
 
}
<!DOCTYPE html> 
 
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> 
 
    <head> 
 
    <meta http-equiv='content-type' content='text/html;charset=utf-8' /> 
 
    <meta name='viewport' content='width=device-width' /> 
 
    <title>Graph</title> 
 
    <link type='text/css' rel='stylesheet' href='css/external.css' /> 
 
    <script type='text/javascript' src='external.js'></script> 
 
    </head> 
 
    <body> 
 
    <div class='main'> 
 
     <canvas id='graph'></canvas> 
 
    </div> 
 
    </body> 
 
</html>

+0

그러나 나에게 도움을 주셔서 감사합니다. 그러나이 솔루션은 도움이되지 않습니다. 시작과 끝 지점이 그래프의 끝에 있기 때문에 시나리오가 효과적이었습니다. 정상적인 경우에는 그렇게하지 않을 것입니다. 그래프는 항상 (0,0)의 원본이 아니며 (width, height)에서 끝나지 않습니다. 비록 내가 거기에 그것을하려고하면, 그것은 그래프에서 이상하게 보일 것이며 잘못된 가격을 나타낼 것입니다. – TypeScripter

+0

그래서 downvote는 기본 수학에 대한 이해가 부족하기 때문에 발생합니다. 당신은 그 x, y 포인트가 당신 자신의 어디에 있었는지 알아낼 수 있어야했습니다. – PHPglue

+0

롤 ... 신의 축복이있다. 나는 너의 위대한 업적을 이룰 수 없다. 인생의 모든 성공을 기원합니다. 계속 응답하고 사람들을 돕는다. – TypeScripter