<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#myCanvas {
box-shadow: 0 0 0 10px red;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="600" height="600"></canvas>
</body>
<script type="text/javascript">
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
var xx = 300;
var yy = 300;
function yuanlai() {
context.fillStyle = "blue";
context.fillRect(150, 150, 100, 100);
context.fill();
}
yuanlai();
context.translate(xx, yy);
function draw() {
context.fillStyle = "#000000";
context.fillRect(-50, -50, 100, 100);
context.fill();
}
draw();
myCanvas.onmousedown = function(e) {
var x = e.offsetX;
var y = e.offsetY;
var sx = x;
var sy = y;
if(x - xx >= -50 && x - xx <= 50 && y - yy >= -50 && y - yy <= 50) {
document.onmousemove = function(ev) {
var ex = ev.offsetX;
var ey = ev.offsetY;
var cx = ex - sx;
var cy = ey - sy;
sx = ex;
sy = ey;
xx = xx + cx;
yy = yy + cy;
if(xx + 50 > 600 || xx - 50 < 0) {
xx = xx - cx;
cx = 0;
}
if(yy + 50 > 600 || yy - 50 < 0) {
yy = yy - cy;
cy = 0;
}
context.translate(cx, cy);
context.clearRect(-xx - 200, -yy - 200, 1000, 1000)
draw();
context.save();
context.translate(-xx, -yy);
yuanlai();
context.restore();
if(xx+50 > 150 && xx-50 < 250 && yy+50 > 150 && yy-50 < 250) {
console.log("碰到了");
}
}
}
}
document.onmouseup = function() {
document.onmousemove = function() {
}
}
</script>
</html>
网友评论