Notes

HTML | 04 canvas标签2

🌸Author Echo Pan


✨Echo有话说

前面我们已经学习了利用canvas画布来绘制矩形、虚实线、圆弧、图像、文字等,还包括颜色、大小等变化。现在让我们来学习更多关于canvas标签的内容。

Canvas教程

路径存储 Path2D

这是一个实验性功能,将绘制的路径存储到path2D对象中。再通过stroke()fill()绘制出来。

该函数支持canvassvg路径。

//新建路径存储
var route1=new Path2D();
route1.rect(10,10,50,50);
//拷贝路径存储
var route2=new Path2D(route1);
route2.moveTo(125,35);
route2.arc(100,35,25,0,Math.PI*2);
//使用Path2D对象作为绘制参数
ctx.stroke(route2);
//使用svg路径
var route3=new Path2D('M10 80 h 50 v 50 h -50 Z');
ctx.fill(route3);
/*
M:moveTo
h:水平位移,horizontal
v:垂直位移,vertical
Z:closePath
大写表示绝对定位,小写表示相对定位
*/

SVG路径Path2D

高清绘图

物理像素 Physical Pixel

物理像素,也叫设备像素,是指设备能控制显示的最小单位,即屏幕分辨率。

设备独立像素 DIP

Device Independent Pixels,逻辑上衡量像素的单位。

物理像素和 DIP 的关联

屏幕分辨率随显示器制造技术的进步而提高,如果在不同分辨率的设备上都用12个物理像素表示字体,那么字体可能会出现扭曲变形,为了让字体能正常显示,就要用逻辑像素来表示字体的大小。1逻辑像素的单位大小可以根据不同的物理像素进行调整,从而使内容在不同设备上都能正常显示。

设备像素比

window.devicePixelRatio是物理像素和设备独立像素的比值,公式为window.devicePixelRatio = 物理像素 / dips

具体实现

网上千篇一律的老办法里涉及到了canvas画布的BackingStorePixelRatio属性,说是canvas缓存里的像素大小,不过该属性已经被废弃了,我们这里先不做探究。

首先我们获取window.devicePixelRatio参数

然后将canvas.widthcanvas.height先赋值给CSS宽高,再将它俩放大window.devicePixelRatio倍,相当于还原成在物理像素中的真实表现。

最后显示的效果是,在更大分辨率中绘制的图形缩小到原始大小的框架中时,会比本来更清晰。

代码:

    var canvas=document.getElementsByTagName("canvas")[0];
    ratio=window.devicePixelRatio||1;
    canvas.style.width=canvas.Width+'px';
    canvas.style.height=canvas.height+'px';
    canvas.width=ratio*canvas.width;
    canvas.height=ratio*canvas.height;
    var ctx=canvas.getContext("2d");
    ctx.arc(canvas.width/2,canvas.height/2,120*ratio,0,Math.PI*2);
    ctx.stroke();

哈哈哈,赞同:

BTW, even though I can empirically confirm that the accepted answer below is correct, I find it fairly amusing that it involves zero explanation of the difference between backingStorePixelRatio and devicePixelRatio. Worse, nobody on the internet seems to have any idea why backingStorePixelRatio ever needed to exist in addition to devicePixelRatio, when that changed, or why that changed. Every seems to be like “Oh, hey, just write these 2 lines of code and you’re good! Bye!”

高分辨率Canvas物理/逻辑像素解决canvas绘制模糊问题

三角函数

饼图和引导线

为什么我们会了解这个,还得从做饼图说起…

做饼图要加个引导线,引导线的起始位置获取思路是,我们要把引导线画在扇形的中线上,我们可以得到扇形圆角/2的度数;

再加上0边到扇形起始边的弧度,可以得到以0边、中线和第三边为边的直角三角形;

再通过三角函数计算得到第三边和0边的长度;

由于圆心位置已知,所以通过两边长度可以得出终点的位置,再从圆心到终点位置画线就可以画出引导线了。

canvas饼图绘制canvas获取arc坐标

简单三角函数

Math.sin(弧度)
Math.cos(弧度)
Math.tan(弧度)

(反)三角函数


上一章:03.canvas标签

下一章:00.开始之前

返回目录