首先想到根据在canvas上鼠标移动,然后再重新画图。但无法确定鼠标前后两次移动的距离,所以无法准确确定图像位置。
而后再根据网上的例子,定义一个div,将div覆盖在图像之上,在移动div的同时,将坐标传给canvas,重新绘制图像。
同时需要熟悉javascript各种坐标
canvas和div标签
<canvas id="myCanvas" width="500" height="400" style="border: 1px solid #c3c3c3;"></canvas>
<div id="cover" style="left: 100px; top: 100px">
</div>
css样式
body { margin: 0; padding: 0; } div { border: solid 1px red; position: absolute; } canvas,div { position: absolute; left: 50px; top: 50px; }
同时注意将javascript代码写在html标签之后
var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext("2d"); var img = new Image(); img.src = "Image/jugg.jpg"; ctx.drawImage(img, 50, 50); var divObj = document.getElementById('cover'); divObj.style.width = img.width + 'px'; divObj.style.height = img.height + 'px'; var x = 0; var y = 0; var moveFlag = false; var clickFlag = false; divObj.onmousedown = function (e) { moveFlag = true; clickFlag = true; var mWidth = e.clientX - this.offsetLeft; var mHeight = e.clientY - this.offsetTop; document.onmousemove = function (e) { clickFlag = false; if (moveFlag) { divObj.style.left = e.clientX - mWidth + 'px'; divObj.style.top = e.clientY - mHeight + 'px'; x = e.clientX - mWidth - canvas.offsetLeft; y = e.clientY - mHeight - canvas.offsetTop; if (e.clientX <= mWidth + canvas.offsetLeft) { divObj.style.left = canvas.offsetLeft + 'px'; x = 0; } if (parseInt(divObj.style.left) + divObj.offsetWidth >= canvas.width + canvas.offsetLeft) { divObj.style.left = canvas.width - divObj.offsetWidth + canvas.offsetLeft + "px"; x = canvas.width - divObj.offsetWidth; } if (e.clientY <= mHeight + canvas.offsetTop) { divObj.style.top = canvas.offsetTop + "px"; y = 0; } if (parseInt(divObj.style.top) + divObj.offsetHeight >= canvas.height + canvas.offsetTop) { divObj.style.top = canvas.height - divObj.offsetHeight + canvas.offsetTop + "px"; y = canvas.height - divObj.offsetHeight; } drawImg(); divObj.onmouseup = function () { moveFlag = false; } } } } function drawImg() { ctx.clearRect(0, 0, 500, 400); ctx.drawImage(img, x, y); ctx.stroke(); }