简体   繁体   中英

Random polygon shapes on HTML5 Canvas

I'm still very new to the canvas element and I'm trying to draw random polygon shapes (triangular shapes) in random places on the canvas element. But I have trouble getting my head around it.

I have this so far, which draws a ploygon nicely, but how to add the randomness and positioning completely eludes me

 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" \\> 

You are trying to get the width and height properties of the Context2D property of your canvas, which both returned undefined .
What you need instead is the canvas element's width and height properties.

Now, since your comment to the other answer, if you need to move the whole shape, just use the first point you saved in posx and posy variables and then adjust the other points positions :

 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(); } } 
 <canvas id="c"><\\canvas> 

Here canvas width and height properties are not set. so when invoke code following line of code, it returns NaN

var width = c2.width;
var height = c2.height;

To get random position try following code base

<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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM