【问题标题】:Draw Multiple figures in a stage using Kineticjs?使用 Kineticjs 在一个舞台上绘制多个图形?
【发布时间】:2013-04-04 02:09:55
【问题描述】:

我想通过点击不同的按钮在画布上绘制多个图形。

HTML

<body>

<div id="container">
</div>

<div id="option">
<button value="rect" onclick="rect();">rect</button>
<button value="circle" onclick="circle();">circle</button>
</div>
</body>

Javascript:

var stage = new Kinetic.Stage({
        container: 'container',
        width: 500,
        height: 500
      });
var layer = new Kinetic.Layer();

function rect(){
var redLine = new Kinetic.Line({
        points: [100, 5, 100, 300, 450,300],
        stroke: 'black',
        strokeWidth: 3,
        lineCap: 'square',
        lineJoin: 'mitter'
      });
// add the shape to the layer

layer.add(redLine);
// add the layer to the stage
stage.add(layer);
}

function circle(){
      var wedge = new Kinetic.Wedge({
        x: stage.getWidth() / 2,
        y: stage.getHeight() / 2,
        radius: 70,
        angleDeg: 60,
        fill: 'red',
        stroke: 'black',
        strokeWidth: 4,
        rotationDeg: -120
      });

      // add the shape to the layer
      layer.add(wedge);

      // add the layer to the stage
      stage.add(layer);
}

但由于未定义层和阶段,因此会出错。我该如何解决?

【问题讨论】:

  • 你能把你的代码放在一个 jsFiddle 里吗?

标签: javascript html canvas kineticjs


【解决方案1】:

没有定义阶段和层的原因是它们超出了范围,或者您的代码在它们首先被实例化之前就被破坏了。

首先,确保你的阶段和层在任何函数之外;全局范围。

其次,单击按钮会调用您的函数“circle()”和“rect()”,我怀疑这会破坏您的代码。您想从内联中删除此 onclick 处理程序:

 <button value="circle" onclick="circle();">circle</button>

并在创建舞台后使用 javascript 分配 onclick。您可以使用 jQuery 轻松分配处理程序。所以你的代码应该是这样的:

HTML

<button value="rect" id='rect'>rect</button>  //assign an id to your button

JS

var stage = new Kinetic.Stage({
    container: 'container',
    width: 500,
    height: 500
  });
var layer = new Kinetic.Layer();

$('#yourButtonId').click(function(){ // button id here would be '#rect' if you use the id above
    rect();
});

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多