What is the canvas tag for?

7

I was searching some information and saw that there is a tag called <canvas> in HTML5.

  • What does canvas tag do?
  • Is it only for geometric shapes?
  • If it is possible and feasible, could you give an example?

In this other question, does the AP talk about the same element <canvas> or does it have nothing to do with HTML5?

    
asked by anonymous 28.06.2017 / 20:07

4 answers

6

The canvas element allows the developer to create images via code. In the case of a Web page, the canvas is controlled with JavaScript. It is not limited to geometric shapes, you can insert images, texts, vectors and control everything with a programming language. That is, you can create animations, interactions, videos and games. It varies according to need and creativity.

The syntax of the element is simple:

<canvas>
  Fallback text for non-supported browsers
</canvas>

That is, if the browser does not have support, the internal text will be displayed on the page. By default, if supported, the content of the element is ignored by the browser.

Your default display setting is display: block and is supported by the vast majority of browsers. See the Can I Use .

Tutorial on how to use the canvas element .

The W3C recommendation for the element can be found here: link

Drawing drawing example with Canvas:

function init() {
  var ctx = document.getElementById("canvas").getContext('2d');
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  var pinta = false;
  var red = green = blue = 127;
  var rf = 1,
    gf = 1,
    bf = 1;
  var rm = getAleatorio();
  var gm = getAleatorio();
  var bm = getAleatorio();

  function desenha(e) {
    var pos = getPosMouse(canvas, e);
    posx = pos.x;
    posy = pos.y;
    if (pinta) {
      ctx.fillStyle = "rgb(" + red + ", " + green + ", " + blue + ")";
      ctx.fillRect(posx - 4, posy - 4, 8, 8);
    }
  }

  canvas.onmousemove = function(e) {
    desenha(e);
    red += rm * rf;
    green += gm * gf;
    blue += bm * bf;

    if (red >= 255 || red <= 0) {
      rf *= -1;
      rm = getAleatorio();
    }
    if (green >= 255 || green <= 0) {
      gf *= -1;
      gm = getAleatorio();
    }
    if (blue >= 255 || blue <= 0) {
      bf *= -1;
      bm = getAleatorio();
    }

  };

  document.getElementById("canvas").onmousedown = function() {
    pinta = true;
  };

  document.getElementById("canvas").onmouseup = function() {
    pinta = false;
  }

  function getPosMouse(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
  }

  function getAleatorio() {
    return Math.floor((Math.random() * 5) + 1);
  }
}

init();
.centralizado {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div>
  <canvas class="centralizado" id="canvas">your browser is nope!</canvas>
</div>
  

Source: Is it possible to save the canvas as an image, and send it to the server?

Example of converting text to image with Canvas:

var canvas = document.getElementById("receipt");
var context = canvas.getContext("2d");

const messages = [
  "################################",
  "Central Jogos",
  "################################",
  "Apostador: test",
  "Valor apostado: R$ 5,00",
  "Valor de retorno: R$ 6,15",
  "Data da aposta: 19/02/2017 15:07",
  "Quantidade de jogos: 1",
  "--------------------------------",
  "Vasco X Flamengo",
  "Empate: 1.23",
  "10/03/2017 15:30",
  "================================",
  "Cambista: Cambista Teste",
  "Telefone: (82) 9977-8877"
];

context.font = "12px Courier new";

y = 12;
for (var i in messages) {
  context.fillText(messages[i], 0, y);
  y += 18;
}

document.getElementById("result").src = context.canvas.toDataURL();
h1 {
  font-size: 16px
}

div {
  float: left;
  padding: 20px;
}
<div>
  <h1>Canvas:</h1>
  <canvas id="receipt" width="230" height="270"></canvas>
</div>
<div>
  <h1>Resultado:</h1>
  <img id="result" alt="Receipt" />
</div>
  

Source: Transform text from one string to another image

Example animation created with Canvas and jQuery

var c = document.createElement("canvas"),
	 $ = c.getContext("2d");

var w = window.innerWidth,
	 h = window.innerHeight;

c.width = w;
c.height = h;

c.addEventListener("mousedown", mouseDown, true);

document.body.appendChild(c);

var part;  //particle 
var meshW = 100;  //mesh width
var dispX = -50;  //x disposition
var dispY = -100;  //y disposition
var partX = 0;  //particle x
var partY = 0;  //particle y
var partIndX = 0;  //particle index x
var partIndY = 0;  //particle index y

var col0 = "rgb(74, 1, ";  //shading color-starts
var col1 = "rgb(0, 3, ";

var partList = [];  //particle array
var gridW = w + meshW;   //grid width 
var gridH = h + meshW * 2;  //grid height

while(partY < gridH)
{
	while(partX < gridW)
	{
		part = new Object(partX, partY, partIndX, partIndY);
		partList.push(part);

		partX += meshW;
		partIndX++;
	}
	
	partX = 0;
	partIndX = 0;
	partY += meshW;
	partIndY++;
}


var partArrayL= partList.length;
var rowCt = Math.ceil( gridW / meshW );  //row count
var colCt = Math.ceil( gridH / meshW );  //column count

$.clearRect(0, 0, w, h);

for(var i = 0; i < partArrayL; ++i)
{
	part = partList[i];
	part.next = partList[i + 1];
	
	if(part.indX % rowCt != rowCt - 1 && part.indY != colCt - 1)
	{
		part.connectAll.push(partList[i + 1]);
		part.connectAll.push(partList[i + rowCt + 1]);
		part.connectAll.push(partList[i + rowCt]);
		part.ready();
	}
}

var int = setInterval(intHandler, 1000 / 30);

function mouseDown()
{
	if(int != undefined)
	{
		clearInterval(int);
		int = undefined;
	}
	else
	{
		int = setInterval(intHandler, 1000 / 30);		
	}
}

part = partList[0];

function intHandler()
{
	$.clearRect(0, 0, w, h);
	
	while(part != undefined)
	{
		part.draw();
		part = part.next;
	}
	
	part = partList[0];
	
	while(part != undefined)
	{
		part.fill();
		part = part.next;
	}
	
	part = partList[0];
}

function Object(pX, pY, pIndX, pIndY)
{
	this.distort = 50;
	
	this.x = dispX + pX + ( Math.random() - Math.random() ) * this.distort;
	this.y = dispY + pY + ( Math.random() - Math.random() ) * this.distort;
	this.indX = pIndX;
	this.indY = pIndY;
	this.color = "hsla(261, 55%, 5%, 1)";  //part border color
		
	this.size = 2;
	this.next = undefined;
	
	this.tracker = (Math.PI / 2) + this.indX * .5;
	this.diffX = Math.random();
	this.diffY = Math.random();
	this.speed = .1;
	this.vol = 30;  //volume  (higher #, more movement)
	
	this.colRngDiff = 70;  //shading variation
  //color range > changing the 225 to vals between 0 and 255, as well as the color range difference # above,  will change base color
	this.colRng = (225 - this.colRngDiff) + Math.floor(Math.random() * this.colRngDiff);
	
	this.draw = function()
	{	
		this.tracker += this.speed;
		this.tracker = this.tracker == 1 ? 0 : this.tracker;
		
		this.x += (Math.sin( this.tracker ) * this.speed) * this.vol;
		this.y += (Math.cos( this.tracker ) * this.speed) * this.vol;
		
	}

	this.readyW = 0;  //start point
	this.readyW1 = 0;

	this.ready = function()
	{
		this.readyW = Math.abs(this.connectAll[0].x - this.x);
		this.readyW1 = Math.abs(this.connectAll[1].x - this.connectAll[2].x);
	}

	
	this.connectAll = [];
	
	this.connect = function()
	{
		if(this.connectAll.length > 0)
		{			
			$.beginPath();
			$.strokeStyle = this.color;
			$.moveTo(this.x, this.y);
	
			for(var j = 0; j < this.connectAll.length; ++j)	
				$.lineTo(this.connectAll[j].x, this.connectAll[j].y);
					
			$.lineTo(this.x, this.y);
			$.lineTo(this.connectAll[1].x, this.connectAll[1].y);
			$.stroke();
		}
	}
	
	this.calcW = 0;
	this.calcW1 = 0;
	
	this.fill = function()
	{		
		if(this.connectAll.length > 0)
		{	
			this.calcW = Math.abs(this.connectAll[0].x - this.x);
			this.calcW1 = Math.abs(this.connectAll[1].x - this.connectAll[2].x);	
						
			$.beginPath();
			$.fillStyle = col0 + (Math.floor((this.readyW / this.calcW) * this.colRng)).toString() + ")";
			
			$.moveTo(this.x, this.y);
			$.lineTo(this.connectAll[2].x, this.connectAll[2].y);
			$.lineTo(this.connectAll[1].x, this.connectAll[1].y);
			$.lineTo(this.x, this.y);
			
			$.fill();
			
			
			$.beginPath();
			$.fillStyle = col1 + (Math.floor((this.readyW1 / this.calcW1) * this.colRng)).toString() + ")";
			
			$.moveTo(this.x, this.y);
			$.lineTo(this.connectAll[1].x, this.connectAll[1].y);
			$.lineTo(this.connectAll[0].x, this.connectAll[0].y);
			$.lineTo(this.x, this.y);
			
			$.fill();
		}		
	}
	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  

Source: link

Example of 'game' created on Canvas

  var C2D, W, H, RC;
  var fps = 24;
  var mspf = 1000 / fps;
  var updateInterval;
  var quit = false;

  function main() {
    var c = document.getElementById('canvas');
    if (c.getContext) {
      initializeCanvas(c);
      var P = new Player(8);
      var L = new Level();
      RC = new RayCaster(C2D, W, H, 4, L, P, input);
      if (initializeLevel()) {
        trace('map loaded successfully.');
        trace("now casting...");
        trace("  \'a\' - turn left");
        trace("  \'d\' - turn right");
        trace("  \'w\' - step forward");
        trace("  \'s\' - step backward");
        trace("  \'q\' - stop casting");
        updateInterval = window.setInterval("update()", mspf);
      }
      else {
        trace("map failed to load");
      }
    }

    else {
      trace('sorry.. you\'ll need a browser that supports the canvas tag,');
      trace('like Safari or Firefox 1.5+ to see this demo.');
    }
  }

  function initializeCanvas(c) {
      C2D = c.getContext('2d');
      C2D.lineWidth = 1;
      C2D.globalAlpha = 1;
      C2D.globalCompositeOperation = 'source-over';
      W = c.width;
      H = c.height;
      trace('canvas initialized');
  }

  function initializeLevel() {
    var mapCells_x = 16;
    var mapCells_y = 16;
    var M = '' +
      '################' +
      '#  @@@@@       #' +
      '#  @   @ % # % #' +
      '#  @       #   #' +
      '#  @  @@       #' +
      '#    &         #' +
      '#   &   P      #' +
      '#  &      &&   #' +
      '#              #' +
      '#  ##  #@%#@%  #' +
      '#  #        #  #' +
      '#  ###      #  #' +
      '#  #        #  #' +
      '#  ######## #  #' +
      '#              #' +
      '################';

    trace('submitting map...');
    return RC.loadMap(M, mapCells_x, mapCells_y);
  }

  function update() {
    if (input.quit) {
      input.quit = false;
      window.clearInterval(updateInterval);
      trace('raycaster halted.');
    }
    else {
      RC.update();
    }
  }
canvas {
  border: 2px solid #000;
  position: absolute;
  left: 33%;
  margin-left: 10px;
}
<script src="https://mdn.github.io/canvas-raycaster/trace.js"></script><linkhref="https://mdn.github.io/canvas-raycaster/trace.css" rel="stylesheet"/>
<script src="https://mdn.github.io/canvas-raycaster/input.js"></script><scriptsrc="https://mdn.github.io/canvas-raycaster/Player.js"></script>
<script src="https://mdn.github.io/canvas-raycaster/Level.js"></script><scriptsrc="https://mdn.github.io/canvas-raycaster/RayCaster.js"></script>

<body onload="main();" onkeydown="press(event);" onkeyup="release(event);">
<div id="trace" class="window"><ul><li>RayCaster v.0.0.1</li></ul></div>
<canvas id="canvas" width="320" height="240"></canvas>
</body>
  

Source: link

    
28.06.2017 / 20:35
3

The tag looks like it's a blank frame, waiting to be painted with a powerful brush called Javascript. :)

Actually, it's much more than that, with the tag you can render images, draw complex elements and create animations.

The good thing is that you can do all this without using any plugin like Flash Player or Silverlight, it's just HTML and Javascript.

Examples

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Seu Navegador não suporta tag canvas</canvas>

    function draw() {
      var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
    }
 <body onload="draw();">
   <canvas id="canvas" width="150" height="150"></canvas>
 </body>

More examples

    
28.06.2017 / 20:31
2
  

In HTML5 Canvas is focused on drawing / processing images with   2D and 3D context

     

Definition by @Gabriel Gartz

Basically they are geometric shapes but it is also composed of images (sprites), the best example for this are games written in HTML5. In the case of games, written side by side with the javascript for the canvas update.

You imagine that the canvas is a space ready to draw.

An easy example is Google Doodles , usually made in HTML5.

Example taken from the Web.

link

var canvas = document.querySelector('canvas');
var ctx    = canvas.getContext('2d');

var x = 50;
var y = 50;

function clearScreen() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawSquare(x, y) {
  ctx.fillRect(x, y, 100, 100);
}

function draw() {
  clearScreen();
  drawSquare(x, y);
  x = x + 5;
  setTimeout(draw, 50);
}

draw();
html, body {
  height: 100%;
  margin: 0;
}
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
canvas {
  width: 300px;
  height: 150px;
}
<canvas></canvas>

It's easy to conclude also that this feature, the canvas, replaced our old Flash. And obviously because it is a native rendering and does not require third-party plugins, an improvement in performance.

    
28.06.2017 / 20:19
0

It is a HTML5 tag that allows you to access methods for creating geometric shapes, making animations, etc.

For example:

var canvas = document.getElementById("minhaCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 80, 80);
<canvas id="minhaCanvas"></canvas>
    
28.06.2017 / 20:19