<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas绘图拖拽</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
list-style: none;
}
body {
background: black;
}
canvas {
background: white;
}
</style>
</head>
<body>
<canvas width=500 height=500 id='canvas'>
您的浏览器版本过低,请更新浏览器
</canvas>
<script type="text/javascript">
var offset = {
x: 50,
y: 50
}
obj = canvas.getContext('2d');
obj.beginPath();
obj.rect(offset.x, offset.y, 200, 100);
obj.strokeStyle = 'blue';
obj.lineWidth = 1;
obj.fillStyle = 'red';
obj.fill();
obj.stroke();
canvas.onmousedown = function (e) {
var ev = e || event;
var l = ev.clientX - offset.x;
var t = ev.clientY - offset.y;
document.onmousemove = function (e) {
var ev = e || event;
clear();
obj.beginPath();
obj.rect(ev.clientX - l, ev.clientY - t, 200, 100);
obj.strokeStyle = 'blue';
obj.lineWidth = 1;
obj.fillStyle = 'red';
obj.fill();
obj.stroke();
};
document.onmouseup = function (e) {
offset.x = e.clientX - l;
offset.y = e.clientY - t;
this.onmousemove = this.onmouseup = null;
};
return false;
}
function clear() {
obj.beginPath();
obj.clearRect(0, 0, canvas.width, canvas.height);
obj.stroke();
}
</script>
</body>
</html>
Canvas绘图拖拽
于 2019-06-16 22:00:17 首次发布