1. 程式人生 > >canvas裡影象拖拽操作

canvas裡影象拖拽操作

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