使用canvas画图,图形模糊怎么办

前端

Winter

2017-09-06

在说解决办法之前,例行惯例,简要的说明一下Html5中的Canvas。Canvas是Html5制图中常用的元素,但其本身并没有绘制能力,它仅仅是图形的容器,要制图还必须依靠脚本。按照Canvas中提供的方法,我们绘制出各种我们想要的图形,本来说这样就已经很棒了,但是有一个致命因素让人很心塞。对美观比较讲究的同学几乎不能忍这个因素,就是绘制的图无比的模糊!!!

所以本人在研究过各种办法,也用过国外大神的库hidpi-canvas-polyfill,但也遇到了一些很难避免的问题。于是经过几次尝试之后,最终采用了一种简单粗暴的办法:将canvas绘制过程放大2倍,然后将整个canvas元素或者其父元素缩小两倍。

我们先看一个没有做过处理的栗子,我们可以看到该栗子画出来的圆,那叫一个模糊,巨丑啊。

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="400" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.fillStyle="yellow";
ctx.arc(200,150,100,0,2*Math.PI);
ctx.stroke();
ctx.fill();

</script> 

</body>
</html>

下面我们再来看看,做放大处理然后再缩小的效果。

<!DOCTYPE html>
<html>
<head>
  <style>
   .container{
     zoom:0.5;
   }
  </style>
</head>
<body>

<div class="container">
  <canvas id="myCanvas" width="800" height="600" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML5 canvas tag.
  </canvas>
</div>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.scale(2,2);
ctx.beginPath();
ctx.fillStyle="yellow";
ctx.arc(200,150,100,0,2*Math.PI);
ctx.stroke();
ctx.fill();

</script> 

</body>
</html>

我们再看效果,画出来的图是不是细腻了许多。

这里我们有几点需要注意:

  • canvas元素的宽和高为之前的两倍
  • 使用ctx.scale(2,2)将绘图放大两倍
  • 在父元素中添加的class中有放大缩小元素的zoom属性,0.5为缩小一倍。当然你也可以用css3中的transform:scale(0.5,0.5)的办法去缩小,只是使用这种方法不会改变布局大小,即canvas虽然视觉上变小了,但它仍旧会占两倍的高和宽。

第8篇《使用canvas画图,图形模糊怎么办》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0条评论