Canvas有一个图像和矩形。图像应该围绕画布的中心旋转,因此我使用平移到达中心但是翻译不允许拖动对象(不知道为什么)。
当我拖动时,图像和矩形应该可以一起拖动。当我旋转时,只有图像应该是可旋转的,矩形应该是静态的(完整到旋转)。
任何人都可以提供以下代码的帮助吗?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
var pi2 = Math.PI * 2;
var resizerRadius = 6;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
x: 0,
y: 0
};
var imageX = 0;
var imageY = 0;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;
var img = new Image();
img.onload = function() {
imageWidth = img.width;
imageHeight = img.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight
draw();
}
img.src = "http://www.w3.org/html/logo/downloads/HTML5_Logo_128.png";
var x = canvas.width / 2, y = canvas.height / 2;
function draw() {
canvas.width = canvas.width;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//I have problem here!
//ctx.translate(x + imageX, y + imageY);
ctx.rotate($('#rvalue').val() * Math.PI / 180);
ctx.drawImage(img, imageX, imageY);
ctx.restore();
ctx.rect(imageX + 160, imageY + 30, 120, 40);
ctx.strokeStyle = "red";
ctx.stroke();
}
function hitImage(x, y) {
return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}
function handleMouseDown(e) {
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
draggingImage = hitImage(startX, startY);
}
function handleMouseUp(e) {
draggingImage = false;
draw();
}
function handleMouseOut(e) {
handleMouseUp(e);
}
function handleMouseMove(e) {
if (draggingImage) {
imageClick = false;
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - startX;
var dy = mouseY - startY;
imageX += dx;
imageY += dy;
imageRight += dx;
imageBottom += dy;
startX = mouseX;
startY = mouseY;
draw();
}
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function(e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function(e) {
handleMouseOut(e);
});
$("#rotate").click(function(event) {
var c = parseInt($('#rvalue').val());
$('#rvalue').val(c + 90);
draw();
});
<!DOCTYPE HTML>
<html lang="en"><head>
<meta charset="UTF-8" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<style type="text/css">#canvas { border: 1px solid #000; }</style>
</head>
<body>
<input type=text value="0" id="rvalue" />
<button id=rotate>Rotate</button><br>
<canvas id="canvas" width=600 height=400></canvas>
</body>
</html>
答案 0 :(得分:1)
我的画布有点生锈,但它有助于翻译,旋转,翻译,然后画画吗?
ctx.translate( centerx, centery );
ctx.rotate( $('#rvalue').val() * Math.PI / 180 );
ctx.translate( -centerx, -centery );
ctx.drawImage(img, imageX, imageY);