这几天在移动端页面用到了canvas画折线图。遇到了两个比较关键的问题。
1.canvas.style.width跟canvas.width(同理,canvas.style.height和canvas.style.height)是两个不同的概念。
canvas.style.width是浏览器渲染canvas的尺寸,而canvas.width是canvas的画布大小。所以不要误以为在css里面设置了canvas的尺寸就OK啦。如果没有设置canvas的width和height属性,则其默认值是width:300px,height:150px。(PS:同时利用style.width,style.height,width,height可控制缩放效果)。
demo:
DOCTYPE html>
<html>
<head>
<title>Demotitle>
<metahttp-equiv="Content-Type"content="text/html; charset=utf-8" />
<scripttype="text/javascript">
functiondrawDiagonal(id){varcanvas=document.getElementByIdx_x(id);varcontext=canvas.getContext("2d");
context.beginPath();
context.moveTo(0,0);
context.lineTo(100,100);
context.stroke();
}
window.οnlοad=function(){
drawDiagonal("diagonal1");
drawDiagonal("diagonal2");
drawDiagonal("diagonal3");
}script>
head>
<body>
<canvasid="diagonal1"style="border:1px solid;"width="100px"height="100px">canvas>
<canvasid="diagonal2"style="border:1px solid;width:200px;height:200px;"width="100px"height="100px">canvas>
<canvasid="diagonal3"style="border:1px solid;width:200px;height:200px;">canvas>
body>
html>
2.canvas在手机上的效果是变模糊了,原因是被自动放大了。所以必须得把canvas放大。大家或许会问到底要放大多少。这是我们需要根据不同的手机的devicePixelRatio(设备像素比,简介文章:http://www.zhangxinxu.com/wordpress/2012/08/window-devicepixelratio/)来进行缩放canvas。