zoom function in javascript

3

I would like to create a zoom function inside an extension file js, I already have a canvas function, however in my drawing it is coming out too small depending on the initial coordinates, so I would like something that when I needed I could give zoom in on the figure. My canvas function is:

function fcanvas(){
var scale = 1;
var originx = 0;
var originy = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath(); 
ctx.strokeStyle = '#000000'; 
ctx.lineWidth = 2; 
ctx.font='20px Arial';
ctx.beginPath();
ctx.moveTo(500,250) 
ctx.lineTo(500,250-(aa)); 
ctx.lineTo(500-(-bb),250 ); 
ctx.lineTo(500,250); 
ctx.font='12px Arial';
ctx.fillText("Tela 1000x500",20,20);
ctx.stroke(); 
}

I would like something easy, or something very detailed, as I'm starting to learn how to program and I do not know many tags yet.

    
asked by anonymous 04.05.2015 / 03:12

1 answer

3

If you want% s of% integer to increase in size, including your drawn content, you can use the CSS property canvas (which applies to any HTML element). If, on the other hand, you want the drawn content to increase in size, just apply the transformation transform in the context of scale (using the canvas and save to limit which part will be staggered).

Example with both transformations:

var zoomXY = 1;   // Zoom (mesmo pro x e pro y)
var escalaXY = 1; // Escala (mesma pro x e pro y)

function fcanvas(){
var scale = 1;
var originx = 0;
var originy = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
  
ctx.clearRect(0, 0, c.width, c.height); // Limpa o canvas antes de desenhar
ctx.save();                             // Salva as transformações
ctx.scale(escalaXY, escalaXY);          // Aplica a escala
  
ctx.beginPath(); 
ctx.strokeStyle = '#000000'; 
ctx.lineWidth = 2; 
ctx.font='20px Arial';
ctx.beginPath();
ctx.moveTo(500,250) 
ctx.lineTo(500,250-(aa)); 
ctx.lineTo(500-(-bb),250 ); 
ctx.lineTo(500,250); 
ctx.font='12px Arial';
ctx.fillText("Tela 1000x500",20,20);
ctx.stroke(); 
  
ctx.restore();                          // Reseta as transformações
}

function zoom(dv) {
  zoomXY += dv;
  document.getElementById("myCanvas").style.transform = "scale(" + zoomXY + ")";
}

function escala(dv) {
  escalaXY += dv;
  fcanvas();
}

var aa = 100;
var bb = 100;
fcanvas();
canvas {
    border: 4px solid black; /* Apenas para ajudar na visualização */

    transform: scale(1);   /* Transformação original (escala 100%) */
    transform-origin: 0 0;
}
Zoom no canvas:
<button onclick="zoom(0.1);">+</button>
<button onclick="zoom(-0.1);">-</button>
Zoom no conteúdo:
<button onclick="escala(0.1);">+</button>
<button onclick="escala(-0.1);">-</button>
<canvas id="myCanvas" width="1000", height="500"></canvas>
    
04.05.2015 / 04:18