问题
Hey I have created a triangle in canvas, I have used 2 methods: main method: createTriangle which called to createInterval 3 times. The triangle is composed of 3 vertices only. Now I want to add zoom option to current canvas. Zoom In and Zoom out, but I don't know from where to start? The problen start from the fact that,I don't have any center point for current triangle and O don't know how to calculate it.
Any guidance will be helpfull :).
Update
What about directives or libraries which can be installed over the canvas?
$(function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//define triangle vertices: 3 vertices for one triangle.
var ver0 = {
x: 114,
y: 366
};
var ver1 = {
x: 306,
y: 30
};
var ver2 = {
x: 498,
y: 366
}
var triangle = [ver0, ver1, ver2]
drawTriangle(triangle);
function drawTriangle(triangle) {
console.log('drawTriangle', triangle);
var v0 = triangle[0];
var v1 = triangle[1];
var v2 = triangle[2];
ctx.beginPath();
createInterval(v0, v1);
createInterval(v1, v2);
createInterval(v0, v2);
ctx.closePath();
}
function createInterval(point1, point2) {
console.log('createInterval', point1, point2);
ctx.moveTo(point1.x, point1.y);
ctx.lineTo(point2.x, point2.y);
ctx.strokeStyle = "black";
ctx.stroke();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=650 height=500></canvas>
回答1:
Given the vertices of a polygon, you can calculate an acceptable zoom point by calculating the arithmetic mean of the vertices X's & Y's. This is actually the polygon's center of mass, but it's a good point to use for zooming.
var sumX=vert0.x+vert1.x+vert2.x;
var sumY=vert0.y+vert1.y+vert2.y;
var zoomX=sumX/3; // 3 vertices
var zoomY=sumY/3;
回答2:
Using the Scale method, you should be able to zoom in and out.
回答3:
From the example. You could do something like this with your triangle function:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<canvas id="myCanvas" width="800" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p>
<button id="zoomIn">+</button>
<button id="zoomOut">-</button>
<script>
$(document).ready(function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeRect(5, 5, 25, 15);
$('#zoomIn').click(function() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.scale(1.10, 1.10);
ctx.strokeRect(5, 5, 25, 15);
});
$('#zoomOut').click(function() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.scale(0.90, 0.90);
ctx.strokeRect(5, 5, 25, 15);
});
});
</script>
</body>
</html>
The zoom increases/decreases the size of your image by 10% each time.
来源:https://stackoverflow.com/questions/36532871/how-to-zoom-to-triangle-in-canvas