HTML画布 - 围绕圆圈的虚线 [英] HTML Canvas - Dotted stroke around circle
问题描述
我知道没有原生支持在画布上渲染点线描边线,但我已经看到了人们能够为此产生支持的聪明方法。
calcPointsCirc
需要4个参数,中心x / y,半径和短划线的长度。它返回一个点数组,x,y,ex,ey。你可以循环通过点绘制虚线圆。可能有更多优雅的方式来做这个,但是有想象的Id给它一个镜头。
function calcPointsCirc(cx,cy, dashLength)
{
var n = rad / dashLength,
alpha = Math.PI * 2 / n,
pointObj = {},
points =
i = -1;
while(i {
var theta = alpha * i,
theta2 = alpha *(i + 1);
points.push({x:(Math.cos(theta)* rad)+ cx,y:(Math.sin(theta)* rad)+ cy,ex:(Math.cos theta; * rad)+ cx,ey:(Math.sin(theta2)* rad)+ cy});
i + = 2;
}
return points;
}
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = canvas.height = 200;
var pointArray = calcPointsCirc(50,50,50,1);
ctx.strokeStyle =rgb(255,0,0);
ctx.beginPath();
for(p = 0; p< pointArray.length; p ++){
ctx.moveTo(pointArray [p] .x,pointArray [p]。
ctx.lineTo(pointArray [p] .ex,pointArray [p] .ey);
ctx.stroke();
}
ctx.closePath();
I do know there is no native support for doing dotted stroke lines rendered on a canvas, but I have seen the clever ways people have been able to generate support for this.
What I am wondering is if there is any way to translate this to allow for rendering dotted strokes around shapes (specifically circles)?
calcPointsCirc
takes 4 arguments, the center x/y, the radius, and the length of the dashes. It returns an array of points, x,y,ex,ey. You can just loop through the points to draw the dashed circle. There's probably much more elegant ways to do this but figured Id give it a shot.
function calcPointsCirc( cx,cy, rad, dashLength)
{
var n = rad/dashLength,
alpha = Math.PI * 2 / n,
pointObj = {},
points = [],
i = -1;
while( i < n )
{
var theta = alpha * i,
theta2 = alpha * (i+1);
points.push({x : (Math.cos(theta) * rad) + cx, y : (Math.sin(theta) * rad) + cy, ex : (Math.cos(theta2) * rad) + cx, ey : (Math.sin(theta2) * rad) + cy});
i+=2;
}
return points;
}
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = canvas.height= 200;
var pointArray= calcPointsCirc(50,50,50, 1);
ctx.strokeStyle = "rgb(255,0,0)";
ctx.beginPath();
for(p = 0; p < pointArray.length; p++){
ctx.moveTo(pointArray[p].x, pointArray[p].y);
ctx.lineTo(pointArray[p].ex, pointArray[p].ey);
ctx.stroke();
}
ctx.closePath();
这篇关于HTML画布 - 围绕圆圈的虚线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!