butiran

canvas js

· 1 min read · edit

result

code

<div id="container">
</div>

<script>
  // get container element, set style
  let cnt = document.getElementById("container");
  cnt.style.marginTop = "1em";
  
  // create button element, set style
  let can = document.createElement("canvas");
  can.width = "300";
  can.height = "150";
  can.style.width = can.width + "px";
  can.style.height = can.height + "px";
  
  // draw on canvas
  let ctx = can.getContext("2d");
  ctx.strokeStyle = "#f00";
  ctx.lineWidth = "2";
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(150, 75);
  ctx.lineTo(300, 75);
  ctx.lineTo(300, 150);
  ctx.stroke()
  
  // append element to container
  cnt.append(can);
</script>

steps

  1. Open a plain text editor, e.g. vim, nano, Notepad++, VS Code.
  2. Copy and paste code given above.
  3. Save with new name, e.g. jstu-06-canvas.html.
  4. View using an internet browser, e.g. Google Chrome, Mozilla Firefox, Apple Safari.
  5. Edit HTML file for further modification.
  6. Save the changes
  7. Refresh internet browser to see updated result.
  8. Repeat the previous three steps (5-7).
  9. Close the internet browser.
  10. Close the plain text editor.