我想通过单击不同的按钮在 Canvas 上绘制多个图形。
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);
}
但是由于未定义图层和阶段,因此会出现错误。我该如何解决?
最佳答案
未定义阶段和层的原因是它们超出了范围,或者您的代码在它们首先实例化之前就被破坏了。
首先,确保您的舞台和图层位于任何功能之外;全局范围。
其次,您的函数“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();
});
关于javascript - 使用 Kineticjs 在一个舞台上绘制多个图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15956272/