canvas js code example

Example 1: javascript canvas

<canvas id="canvas"></canvas>
<script>

	var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
  
	ctx.beginPath();
	ctx.rect(x, y, width, height);
  	ctx.fillStyle = 'limegreen';
  	ctx.fill();
  
  	ctx.beginPath();
  	ctx.arc(x, y, radius, startAngle, endAngle, counterClockWise(optional));
  	ctx.strokeStyle = 'black';
  	ctx.stroke();

</script>

Example 2: javascript create canvas

var canvas = document.createElement("canvas"); //Create canvas
document.body.appendChild(canvas); //Add it as a child of <body>

Example 3: canvas nodejs

const { createCanvas, loadImage } = require('canvas')const canvas = createCanvas(200, 200)const ctx = canvas.getContext('2d') // Write "Awesome!"ctx.font = '30px Impact'ctx.rotate(0.1)ctx.fillText('Awesome!', 50, 100) // Draw line under textvar text = ctx.measureText('Awesome!')ctx.strokeStyle = 'rgba(0,0,0,0.5)'ctx.beginPath()ctx.lineTo(50, 102)ctx.lineTo(50 + text.width, 102)ctx.stroke() // Draw cat with lime helmetloadImage('examples/images/lime-cat.jpg').then((image) => {  ctx.drawImage(image, 50, 0, 70, 70)   console.log('<img src="' + canvas.toDataURL() + '" />')})

Example 4: javascritp canvas

//Creates a canvas and draws a circle
var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, 50, 0, Math.PI * 2);
ctx.fillStyle = "red";
ctx.strokeStyle = "black";
ctx.stroke();
ctx.fill();

Example 5: javascript canvas

#this code creates a circle within a canvas that must be created in HTML
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

Example 6: canvas in javascript

<!DOCTYPE HTML>

<html>
   <head>
   
      <style>
         #mycanvas{border:1px solid red;}
      </style>
   </head>
   
   <body>
      <canvas id = "mycanvas" width = "100" height = "100"></canvas>
   </body>
</html>

Tags:

Html Example