O elemento canvas
permite o desenvolvedor criar imagens via código. Tratando-se de uma página Web, controla-se o canvas com JavaScript. Não é limitado à formas geométricas, você pode inserir imagens, textos, vetores e controlar tudo com uma linguagem de programação. Ou seja, você pode criar animações, interações, vídeos e jogos. Varia conforme a necessidade e criatividade.
A sintaxe do elemento é simples:
<canvas>
Fallback text for non-supported browsers
</canvas>
Isto é, se o navegador não possuir suporte, o texto interno será exibido na página. Por padrão, se suportado, o conteúdo do elemento é ignorado pelo navegador.
Sua configuração padrão de exibição é display: block
e é suportado pela grande maioria dos navegadores. Veja no Can I Use.
Tutorial de como utilizar o elemento canvas
.
A recomendação W3C do elemento pode ser encontrada aqui: https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
Exemplo de prancheta de desenho com 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>
Fonte: É possível salvar o canvas como imagem, e enviar ao servidor?
Exemplo de conversão de texto para imagem com 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>
Fonte: Transformar texto de uma string em imagem
Exemplo de animação criado com Canvas e 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>
Fonte: http://www.html5canvastutorials.com/advanced/canvas-shape-and-color-effects/
Exemplo de 'jogo' criado no 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>
<link href="https://mdn.github.io/canvas-raycaster/trace.css" rel="stylesheet"/>
<script src="https://mdn.github.io/canvas-raycaster/input.js"></script>
<script src="https://mdn.github.io/canvas-raycaster/Player.js"></script>
<script src="https://mdn.github.io/canvas-raycaster/Level.js"></script>
<script src="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>
Fonte: https://mdn.github.io/canvas-raycaster/