canvas画天气预报
问题一:画直线时候,画面失贞,纵坐标明明只有200大小,但是已经超出画面范围,线条也很粗:
解决:百度到类似问题:http://www.tuicool.com/articles/qMnAjm
分析:原来自己在css样式里面将这个画布canvas的尺寸设置成了页面全屏;然而html5 canvas的浏览器canvas默认大小是300px*150px;相当于一张图片css设置之后会对图片进行拉伸变化,而canvas非矢量图,所以会失真,高度也会按照拉伸比例变化。
此时只要将canvas用js设置为css样式设置的全屏尺寸就行了。
附下修改后的部分代码:
html,body{ padding: 0; margin: 0; } canvas{ width: 100%; }
var myCav=document.getElementById("canvas_draw"); var myCxt=myCav.getContext("2d"); var width=myCav.scrollWidth; var height=myCav.scrollHeight; myCav.width=width; myCav.height=height;
function drawBackText(myCxt,width,height){ myCxt.fillStyle="#001122"; myCxt.fillRect(0,0,width,height); } function drawLines(myCxt,data,width,height){ var max = data.reduce(function(pre,cur,inde,arr){ return pre>cur?pre:cur; }); var i,len=data.length; var cellHeight=height/max; var cellWeidth=width/len; myCxt.beginPath(); myCxt.moveTo(0,height-cellHeight*data[i]); //height*(data[i]/max)); for(i=1;i<len;i++){ myCxt.lineTo(i*cellWeidth,height-height*(data[i]/max)); } myCxt.strokeStyle = 'rgba(255,0,0,0.5)'; myCxt.stroke(); }
var dataObj={"type":"day","tempData":[12,18,16,20,24,16,14,15,15,16,11,16,17,17,20,20,22,11,2,24,12,1,44,11,14,22,10,18,17,15,9,8,6,18,28,10,23,26,18,29,30,31]};
function draw(){ var myCav=document.getElementById("canvas_draw"); var myCxt=myCav.getContext("2d"); var width=myCav.scrollWidth; var height=myCav.scrollHeight; myCav.width=width; myCav.height=height; drawBackText(myCxt,width,height); drawLines(myCxt,dataObj.tempData,width,height); } window.onload=draw();
<canvas id="canvas_draw"> <p>Your browserdoes not support the canvas element!</p> </canvas>