drawCode.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function randomNum(min, max) {
  2. return Math.floor(Math.random() * (max - min) + min);
  3. }
  4. function randomColor(min, max) {
  5. var _r = randomNum(min, max);
  6. var _g = randomNum(min, max);
  7. var _b = randomNum(min, max);
  8. return "rgb(" + _r + "," + _g + "," + _b + ")";
  9. }
  10. function drawPic(code) {
  11. var $canvas = document.getElementById("canvas");
  12. var _str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  13. var _picTxt = "";
  14. var _num = 4;
  15. var _width = $canvas.width;
  16. var _height = $canvas.height;
  17. var ctx = $canvas.getContext("2d");
  18. ctx.textBaseline = "bottom";
  19. ctx.fillStyle = randomColor(180, 240);
  20. ctx.fillRect(0, 0, _width, _height);
  21. for(var i = 0; i < _num; i++) {
  22. var x = (_width - 10) / _num * i + 10;
  23. var y = randomNum(_height, _height);
  24. var deg = randomNum(-25, 25);
  25. var txt = code[i];
  26. _picTxt += txt;
  27. ctx.fillStyle = randomColor(10, 100);
  28. ctx.font = randomNum(16, 30) + "px SimHei";
  29. ctx.translate(x, y);
  30. ctx.rotate(deg * Math.PI / 180);
  31. ctx.fillText(txt, 0, 0);
  32. ctx.rotate(-deg * Math.PI / 180);
  33. ctx.translate(-x, -y);
  34. }
  35. for(var i = 0; i < _num; i++) {
  36. ctx.strokeStyle = randomColor(90, 180);
  37. ctx.beginPath();
  38. ctx.moveTo(randomNum(0, _width), randomNum(0, _height));
  39. ctx.lineTo(randomNum(0, _width), randomNum(0, _height));
  40. ctx.stroke();
  41. }
  42. for(var i = 0; i < _num * 10; i++) {
  43. ctx.fillStyle = randomColor(0, 255);
  44. ctx.beginPath();
  45. ctx.arc(randomNum(0, _width), randomNum(0, _height), 1, 0, 2 * Math.PI);
  46. ctx.fill();
  47. }
  48. return _picTxt;
  49. }