使用加密事件

时间:2018-03-07 16:33:36

标签: html canvas

让我试着解释一下我要做的事情。我的画布尺寸为500 x 500,我画了一个三角形。使用键上事件可以在画布中随机复制这个三角形吗?

到目前为止,我有这个:

HTML

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>Canvas</title>
   <script src="canvas.js" type="text/javascript" defer></script>
</head>
<body onload="setUp()">
    <h1>Triangle</h1>
    <canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>

    <br>
    <button type="button" id="resetbtt" name="button">Reset</button>

</body>

</html>

JS:

let canvas;
let ctx;
let dx = 10;
let dy = 10;
let x = 250;
let y = 250;
let WIDTH, HEIGHT = 500;


function setUp(){
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   let resetbtt = document.getElementById('resetbtt');
   drawTriangle();
}

function drawTriangle(){

    ctx.save();
    ctx.translate(x,y)
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(-15, 15);
    ctx.lineTo(15, 15);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();

我不知道如何设置副本

1 个答案:

答案 0 :(得分:0)

let canvas;
let ctx;
let dx = 10;
let dy = 10;
let WIDTH, HEIGHT = 500;


function setUp() {
  canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  let resetbtt = document.getElementById('resetbtt');
  drawTriangle(250, 250);
}
//little transfor your function - add parameters X and Y - this is start to draw
function drawTriangle(x, y) {

  ctx.save();
  ctx.beginPath();
  ctx.translate(x, y);
  ctx.moveTo(0, 0);
  ctx.lineTo(-15, 15);
  ctx.lineTo(15, 15);
  ctx.closePath();
  ctx.stroke();
  ctx.restore();

}
//this small function get random int number
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
//add event Listener when press key
document.body.onkeyup = function(e) {
  if (e.keyCode == 32) {//32 is keyCode space
    var x = getRandomArbitrary(20, 450),
      y = getRandomArbitrary(20, 450);
    drawTriangle(x, y);
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Canvas</title>
</head>

<body onload="setUp()">
  <h1>Triangle</h1>
  <canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>

  <br>
  <button type="button" id="resetbtt" name="button">Reset</button>

</body>

</html>