我使用javascript在画布上画了几行,我正在改变3个不同行(两个轴,底部10行和前10行)的线宽值。当我更改前2行的lineWidth
属性(lineWidth = 2.5和lineWidth = 1.0)时,它可以正常工作。但是,当我添加最后一个lineWidth属性= 2.0时,它不起作用,它会更改。我把代码放在这个小提琴里。任何帮助将不胜感激。
http://jsfiddle.net/pwp2ps09/1/
<canvas id="graph" width="550" height="400"></canvas>
$(document).ready(function(){
var p= 50;
graph = $('#graph');
var g = graph[0].getContext('2d');
drawlines();
function drawlines(){
g.beginPath();
//brings cursor to the origin of this line graph
g.moveTo(p, graph.height() - p);
//creates x-axis
g.lineTo(graph.width() - p, graph.height() - p);
g.moveTo(p, graph.height() - p);
//creates y-axis
g.lineTo(p, p);
g.lineWidth = 2.5;
g.font = '12px Arial';
g.stroke();
g.lineWidth = 1.0;
for (i=10; i<101; i+=10){
g.moveTo(p, graph.height() - p - i);
//creates x-axis
g.lineTo(graph.width() - p, graph.height() - p - i);
}
g.stroke();
g.lineWidth = 2.0;
for (i=110; i<201; i+=10){
g.moveTo(p, graph.height() - p - i);
//creates x-axis
g.lineTo(graph.width() - p, graph.height() - p - i);
}
g.stroke();
}
});
答案 0 :(得分:2)
在添加新行之前,请务必使用beginPath()
。路径将使用最新设置的线宽进行渲染。 beginPath()
将清除上一个路径和添加的行。
如果您没有清除路径,则新的stroke()
电话将在旧线路的顶部划线新添加的线路。由于线宽较粗,新线只会过度粗略。
更新了代码(来自小提琴):
$(document).ready(function() {
var p = 50;
graph = $('#graph');
var g = graph[0].getContext('2d');
drawlines();
function drawlines() {
g.beginPath();
//brings cursor to the origin of this line graph
g.moveTo(p, graph.height() - p);
//creates x-axis
g.lineTo(graph.width() - p, graph.height() - p);
g.moveTo(p, graph.height() - p);
//creates y-axis
g.lineTo(p, p);
g.lineWidth = 2.5;
g.font = '12px Arial';
g.stroke();
g.beginPath(); // <--- Define new path here
g.lineWidth = 1.0;
for (i = 10; i < 101; i += 10) {
g.moveTo(p, graph.height() - p - i);
//creates x-axis
g.lineTo(graph.width() - p, graph.height() - p - i);
}
g.stroke();
g.beginPath(); // <--- and here, etc.
g.lineWidth = 2.0;
for (i = 110; i < 201; i += 10) {
g.moveTo(p, graph.height() - p - i);
//creates x-axis
g.lineTo(graph.width() - p, graph.height() - p - i);
}
g.stroke();
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="graph" width="550" height="400"></canvas>
&#13;