javascript不受canvas大小改动影响 实现绘制坐标轴

今天实在闲来蛋疼,群里遇到一位好友利用canvas绘制曲线图像出问题了,当然了作为一个灰常热心滴小盆友的我当然不免去看看问题了,帮助这位朋友解决完问题以后发现,他的canvas绘制过程中是固定大小,所有绘制都是写死的。这样肿么扩展,为了他好,我就动手写了一个canvas可以任意改变demo......调试了一下,绘制木有问题了,分享一下!!!!(由于在家纯记事本打出来的,看了一下没有报错,要是有分号该写没写的,请提醒我,谢谢。)x、y轴的绘制间距为20px

转载请著名地址,谢谢

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" /> </script>

<canvas id="controlCanvas" height="519" width="1035" ></canvas>//高宽任你调整
<button id="changeSize">变化大小</button>
<script type="text/javascript" src="jquery-1.6.4.min.js" /> </script>
<script type="text/javascript">

$(function(){
init();

$("#changeSize").click(function(){
$("#controlCanvas").attr("height",800);
$("#controlCanvas").attr("width",1100);

init();
});

})
function init() 
{

var canvas = document.getElementById("controlCanvas"); 
var context = canvas.getContext("2d"); 
var canvasWidth=$(canvas).attr("width");//获取canvas的宽度

var canvasHeight=$(canvas).attr("Height");//获取canvas的高度
var canvasWidthFloat=canvasWidth%20; //防止canvas宽度不是20的倍数,要不然绘制的坐标点会有问题
var canvasHeightFloat=canvasHeight%20; //防止canvas高度不是20的倍数,要不然绘制的坐标点会有问题
//绘制y轴平行线
for ( var x = 20; x <canvasWidth-20; x += 20) { 
context.moveTo(x, canvasHeightFloat); 
context.lineTo(x, canvasHeight-20); 
} 
//绘制x轴平行线
for ( var y = 20; y <canvasHeight-20; y += 20) { 
context.moveTo(20, y+canvasHeightFloat); 
context.lineTo(canvasWidth-20, y+canvasHeightFloat); 
} 
context.strokeStyle = "#ddd"; 
context.stroke(); 
context.beginPath(); 
//画横坐标 
context.moveTo(20, canvasHeight-20); 
context.lineTo(canvasWidth-20, canvasHeight-20); 
context.moveTo(canvasWidth-35, canvasHeight-30); 
context.lineTo(canvasWidth-20, canvasHeight-20); 
context.lineTo(canvasWidth-35, canvasHeight-10); 
//画纵坐标 
context.moveTo(20, canvasHeight-20); 
context.lineTo(20, canvasHeightFloat); 
context.moveTo(10, canvasHeightFloat+15); 
context.lineTo(20, canvasHeightFloat); 
context.lineTo(30, canvasHeightFloat+15);



context.strokeStyle = "#000"; 
context.stroke(); 
var yvalue=0
var yvalueMax=parseInt((canvasHeight-20)/20)
//这样你的y坐标就不会受到canvas变法而烦恼了
for(var x=20;x<canvasHeight;x+=20)
{
if(yvalue==yvalueMax)
break;
context.fillText(yvalue++,5,canvasHeight-x+3);//让y轴的值向下移动3px,让y值显示在平行线的中间
}
//x轴坐标,这里修复了一下canvas不是20倍数以后,坐标点为移动的问题 -_-!经过测试,无论你怎么调整都没事哦
var xvalue=parseInt((canvasWidth-20)/20)-1
for(var y=20;y<canvasWidth;y+=20)
{
if(xvalue==0)
break;
context.fillText(xvalue--,canvasWidth-y-canvasWidthFloat-3,canvasHeight-5);//让x轴的值向右移动3px,让x值显示在平行线的中间
}

}


</script>

posted on 2011-11-20 02:25  牛-_-蜗  阅读(4106)  评论(5编辑  收藏  举报

导航