如何让用户绘制椭圆形?

时间:2019-04-27 12:29:02

标签: javascript html5-canvas

我正在用JavaScript制作一个简单的绘画程序。圆形工具按预期工作,但是如何添加用于绘制椭圆/椭圆形的工具?

我已经重用了许多代码来制作不同的工具(铅笔,直线,矩形和圆形),到目前为止,效果很好。但是我无法获得正确绘制椭圆的代码。

这是绘制随机颜色填充的圆形的当前代码和工作代码:

var radius = Math.max(
Math.abs(ev._x - tool.x0),
Math.abs(ev._y - tool.y0)
) / 2;

var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;

context.fillStyle = 'hsl(' + 360 * Math.random() + ', 85%, 50%)';
context.beginPath();
context.arc(x, y, radius, 0, Math.PI*2, false);
context.stroke();
context.closePath();
context.fill();

我试图将其与已在使用的代码和context.scale集成在一起,但我做错了:

var radius = Math.max(
Math.abs(ev._x - tool.x0),
Math.abs(ev._y - tool.y0)
) / 2;

var radius2 = ;

var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;

context.save();
context.scale(1,  radius2/radius);
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.restore();
context.lineWidth=2;
context.strokeStyle="#000";
context.stroke();  

var半径是否正确,我是否写var radius2?整个代码在这里JS Bin

1 个答案:

答案 0 :(得分:0)

  1. x属性定义椭圆中心的x坐标
  2. y属性定义椭圆中心的y坐标
  3. radiusX属性定义水平半径
  4. ry属性定义垂直半径

图片供您参考enter image description here