我还是画布元素的新手,我试图在canvas元素的随机位置绘制随机多边形形状(三角形)。但是我无法理解它。
到目前为止,我有这个,很好地画了一个ploygon,但是如何添加随机性和定位完全没有我
var c = document.getElementById('c');
if (c.getContext) {
c2 = c.getContext('2d');
var width = c2.width;
var height = c2.height;
var maxAmount = 20;
for (i = 0; i < maxAmount; i++) {
var polySize = 50;
var posx = (Math.random() * (width - polySize)).toFixed();
var posy = (Math.random() * (height - polySize)).toFixed();
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(posx, posy);
c2.lineTo(100, 50);
c2.lineTo(50, 100);
c2.lineTo(0, 90);
c2.closePath();
c2.fill();
}
}
<canvas id="c" \>
答案 0 :(得分:2)
您正在尝试获取画布的Context2D
属性的宽度和高度属性,这两个属性都返回undefined
。
您需要的是canvas
元素的宽度和高度属性。
现在,由于您对其他答案的评论,如果您需要移动整个形状,只需使用您在posx
和posy
变量中保存的第一个点,然后调整其他点位置:
var c = document.getElementById('c');
c.width =500;
c.height= 500;
if (c.getContext) {
var c2 = c.getContext('2d');
var width = c.width;
var height = c.height;
var maxAmount = 20;
for (var i = 0; i < maxAmount; i++) {
var polySize = 50;
var posx = (Math.random() * (width - polySize));
var posy = (Math.random() * (height - polySize));
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(posx, posy);
c2.lineTo(posx+100, posy+50);
c2.lineTo(posx+50,posy+100);
c2.lineTo(posx+0, posy+90);
c2.closePath();
c2.stroke();
c2.fill();
}
}
&#13;
<canvas id="c"><\canvas>
&#13;
答案 1 :(得分:0)
此处未设置画布宽度和高度属性。所以当在代码行之后调用代码时,它返回NaN
var width = c2.width;
var height = c2.height;
要获得随机位置,请尝试以下代码库
<canvas id="c" width="250" height="250" \>
var c = document.getElementById('c');
if (c.getContext)
{
c2 = c.getContext('2d');
var width = c.width;
var height = c.height;
var maxAmount = 5;
for (i = 0; i < maxAmount; i++) {
var polySize = 50;
var posx = (Math.random() * (width - polySize)).toFixed();
var posy = (Math.random() * (height - polySize)).toFixed();
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(posx, posy);
c2.lineTo(100, 50);
c2.lineTo(50, 100);
c2.lineTo(0, 90);
c2.closePath();
c2.fill();
}
}