p5.j​​s:颜色随机,另存为pdf函数

时间:2019-12-08 21:43:33

标签: javascript html p5.js

这是我的代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
<script>
var angle = 0;

function setup() {
  createCanvas(710, 400);
  background(255, 0, 0);
  noStroke();
  fill(0, 102);
}

function draw() {
  if (mouseIsPressed === true) {
    angle += 5;
    var val = cos(radians(angle)) * 20.0;
    for (var a = 0; a < 360; a += 75) {
      var xoff = cos(radians(a)) * val;
      var yoff = sin(radians(a)) * val;
      fill(random(0, 255));
      ellipse(mouseX, mouseY, random(20, 120), random(20, 120));
    }
  }
}
</script>

<button>Save as PDF</button>

我需要:

A)对象的颜色当前为灰色(从白色到黑色)。我需要随机排列三个不同的红色。怎么编码呢?

B)“另存为PDF”按钮应该起作用...

1 个答案:

答案 0 :(得分:1)

对于A部分,您可以这样做

fill(random(0, 255),random(0, 255),random(0, 255))

但是我建议您再看看P5.js文档,以了解其原因和工作原理

对于B: 您可以尝试使用jsPDF

<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<canvas id="myCanvas" width="578" height="200"></canvas>
<button id="download">download</button>
<script>
  var download = document.getElementById('download');
  download.addEventListener("click", function() {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    // only jpeg is supported by jsPDF
    var imgData = canvas.toDataURL("image/jpeg", 1.0);
    var pdf = new jsPDF();
    pdf.addImage(imgData, 'JPEG', 0, 0);
    pdf.save("download.pdf");
  }, false);
</script>