如何在Canvas中绘制自定义形状?

时间:2016-05-11 09:45:49

标签: html html5 html5-canvas

我试图绘制自定义形状,但因为我使用moveTo ..我不能填充它,所以我的问题是有任何方法可以确定屏幕上的点填充形状?或者这样做我最常使用或在与图层相同的块中绘制另一个真实形状...

看看我的例子,画一个简单的形状: Custom shape before & after fill

我可以用蓝色填充图像我画了一个填充矩形,那么这是一个真正的方法吗?

填充前的形状代码:

var canvas3 = document.getElementById('canvas3'); 
        var c3 = canvas3.getContext('2d'); 
        c3.fillStyle = 'green';
        c3.beginPath();
        c3.moveTo(10,30);
        c3.lineTo(200,30);
        c3.moveTo(10,80);
        c3.lineTo(200,80);
        c3.moveTo(10,30);
        c3.lineTo(10,180);
        c3.moveTo(200,30);
        c3.lineTo(200,180);
        //c3.closePath();
        c3.fill();
        c3.lineWidth = 5;
        c3.strokeStyle = 'orange';
        c3.stroke();

填充后的形状代码:

var canvas3 = document.getElementById('canvas3'); 
        var c3 = canvas3.getContext('2d'); 
        c3.fillStyle = 'blue';
        c3.beginPath();
        c3.moveTo(10,30);
        c3.fillRect(10,30,190,60);
        c3.moveTo(10,30);
        c3.lineTo(10,180);
        c3.moveTo(10,90);
        c3.lineTo(200,90);
        c3.moveTo(200,30);
        c3.lineTo(200,180);
        c3.moveTo(10,30);
        c3.lineTo(200,30);
        //c3.closePath();
        c3.fill();
        c3.lineWidth = 5;
        c3.strokeStyle = 'orange';
        c3.stroke();

最后哪种方式可以画出这样的形状? 注意:我是新的html5画布,我从this online book读取。

1 个答案:

答案 0 :(得分:2)

  

有什么方法可以确定屏幕上的点来填充   形状?或者这样做我最常使用或绘制另一个真正的形状   阻止作为图层

只需在同一个地方画一个形状。之后先填充然后中风。画布可能需要进行一些规划,以便绘制事物的顺序。

如果您打算经常重绘或移动它们,可以定义保存几何数据的对象。这肯定会在以后简化目标。

  

哪种方式可以画出这样的形状?

在我看来,这段代码可以更简单,代码更少。如果您可以使用简单的方法绘制形状,则无需像在代码中那样分解几个部分的形状。在这种情况下,可以用一个矩形替换四行。

知道如何在内部绘制这些形状也有助于我们利用rect()离开的路径,即在左上角关闭,以便我们可以从那里继续。

例如:



var c3 = c.getContext("2d");

// fill blue box first as it will be at the bottom
c3.rect(10, 30, 190, 50);  // x, y, width, height
c3.fillStyle = 'blue';
c3.fill();

// orange stroke
// we know rect() will close at upper-left corner so continue from there with left leg
c3.lineTo(10, 180);
c3.moveTo(200, 80);        // create second leg at right separately
c3.lineTo(200, 180); 

c3.strokeStyle = "orange";
c3.lineWidth = 5;
c3.lineJoin = c3.lineCap = "round";
c3.stroke();

<canvas id=c height=180></canvas>
&#13;
&#13;
&#13;

另一种方法是填充然后构建线路径:

&#13;
&#13;
var c3 = c.getContext("2d");

c3.fillStyle = 'blue';
c3.fillRect(10, 30, 190, 50); // fillRect does not add to path

// orange stroke
c3.moveTo(10, 180);           // create "housing" starting at bottom-left corner
c3.lineTo(10, 30);            // upper-left
c3.lineTo(200, 30);           // upper-right
c3.lineTo(200, 180);          // bottom-right

c3.moveTo(10, 80);            // add cross-bar
c3.lineTo(200, 80); 

c3.strokeStyle = "orange";
c3.lineWidth = 5;
c3.lineJoin = c3.lineCap = "round";
c3.stroke();
&#13;
<canvas id=c height=180></canvas>
&#13;
&#13;
&#13;

相关问题