[英]Random polygon shapes on HTML5 Canvas
我對canvas元素仍然很陌生,我試圖在canvas元素上的隨機位置繪制隨機多邊形(三角形)。 但是我很難解決這個問題。
到目前為止,我已經掌握了很好的方法,但是如何添加隨機性和位置完全使我難以理解
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" \\>
您正在嘗試獲取畫布的Context2D
屬性的width和height屬性,它們均返回undefined
。
相反,您需要的是canvas
元素的width和height屬性。
現在,由於對對方的回答您的意見,如果你需要移動的整體造型,只是利用你保存了第一點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(); } }
<canvas id="c"><\\canvas>
此處未設置畫布的width和height屬性。 因此,當在代碼行之后調用代碼時,它返回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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.