Показать сообщение отдельно
  #8 (permalink)  
Старый 16.05.2017, 08:48
Профессор
Отправить личное сообщение для Rise Посмотреть профиль Найти все сообщения от Rise
 
Регистрация: 07.11.2013
Сообщений: 4,662

Sasha05082002, так?
<style>
canvas { outline: 1px solid gray; }
canvas:hover { outline-color: red; }
</style>
<canvas width="400" height="200" tabindex="1"></canvas>
<script>
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
context.fillText('Touch Me', canvas.width / 2, canvas.height / 2);
var requestID;
var Mouse = {
	x: 0,
	y: 0,
	angle: 0,
	follow: 0,
	info: function() {
		context.fillText('Mouse: angle ' + this.angle + ' x ' + this.x + ' y ' + this.y + ' follow ' + this.follow, 5, 10);
	}
};
var Tower = {
	x: canvas.width / 2,
	y: canvas.height / 2,
	angle: 0,
	width: 60,
	height: 40,
	degree: Math.PI / 180,
	left: function() {
		var angle = this.angle - this.degree;
		this.angle = (angle < 0) ? angle + 2 * Math.PI : angle;
	},
	right: function() {
		var angle = this.angle + this.degree;
		this.angle = (angle < 2 * Math.PI) ? angle : angle - 2 * Math.PI;
	},
	step: function() {
		if (Mouse.follow) {
			var angle = Math.atan2(Mouse.y - this.y, Mouse.x - this.x);
			Mouse.angle = (angle < 0) ? angle + 2 * Math.PI : angle;
			if (Mouse.angle < this.angle) {
				angle = this.angle - Mouse.angle;
				(angle < Math.PI) ? this.left() : this.right();
			} else {
				angle = Mouse.angle - this.angle;
				(angle < Math.PI) ? this.right() : this.left();
			}
			if (angle - this.degree < 0) Mouse.follow = 0;
		}
	},
	draw: function() {
		var x1, y1, x2, y2;
		context.save();
		context.translate(this.x, this.y);
		context.rotate(this.angle);
		context.translate(-this.x, -this.y);
		x1 = this.x - this.width / 2;
		y1 = this.y - this.height / 2;
		x2 = x1 + this.width;
		y2 = y1 + this.height;
		context.beginPath();
		context.moveTo(x1, y1);
		context.lineTo(x2, y1);
		context.lineTo(x2 + 10, this.y);
		context.lineTo(x2, y2);
		context.lineTo(x1, y2);
		context.fill();
		context.restore();
	},
	info: function() {
		context.fillText('Tower: angle ' + this.angle, 5, 20);
	}
};
canvas.addEventListener('mouseenter', function(e) {
	this.focus();
	requestID = requestAnimationFrame(function tick() {
		context.clearRect(0, 0, canvas.width, canvas.height);
		Tower.step();
		Tower.draw();
		Tower.info();
		Mouse.info();
		requestID = requestAnimationFrame(tick);
	});
});
canvas.addEventListener('mouseleave', function(e) {
	cancelAnimationFrame(requestID);
});
canvas.addEventListener('mousemove', function(e) {
	Mouse.follow = 1;
	Mouse.x = e.offsetX;
	Mouse.y = e.offsetY;
});
</script>

Последний раз редактировалось Rise, 22.05.2017 в 22:57.
Ответить с цитированием