首先想到根據在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(); }