今天實在閑來蛋疼,群裡遇到一位好友利用canvas繪制曲線圖像出問題瞭,當然瞭作為一個灰常熱心滴小盆友的我當然不免去看看問題瞭,幫助這位朋友解決完問題以後發現,他的canvas繪制過程中是固定大小,所有繪制都是寫死的。這樣腫麼擴展,為瞭他好,我就動手寫瞭一個canvas可以任意改變demo……調試瞭一下,繪制木有問題瞭,分享一下!!!!(由於在傢純記事本打出來的,看瞭一下沒有報錯,要是有分號該寫沒寫的,請提醒我,謝謝。)x、y軸的繪制間距為20px
轉載請著名地址,謝謝
<script type="text/javascript" src="https://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>
作者 牛-_-蝸