我在下面的代碼中添加了一個矩形到畫布,我對此有一些問題。在HTML5畫布中移動,刪除和檢索添加的矩形位置
- 是否可以在添加的矩形創建後移動?
- 是否可以刪除已添加的矩形?
我可以找回後,我已經添加了一堆矩形,並讓通過點擊按鈕說所有添加的矩形位置(X,Y,寬度和高度)?
<script> function rect() { var canvas = document.getElementById('drawing'), ctx = canvas.getContext('2d'), rect = {}, drag = false; function init() { canvas.addEventListener('mousedown', mouseDown, false); canvas.addEventListener('mouseup', mouseUp, false); canvas.addEventListener('mousemove', mouseMove, false); } function mouseDown(e) { rect.startX = e.pageX - this.offsetLeft; rect.startY = e.pageY - this.offsetTop; drag = true; } function mouseUp() { drag = false; } function mouseMove(e) { if (drag) { rect.w = (e.pageX - this.offsetLeft) - rect.startX; rect.h = (e.pageY - this.offsetTop) - rect.startY ; //ctx.clearRect(0,0,canvas.width,canvas.height); draw(); } } function draw() { ctx.globalAlpha=0.5; // Half opacity ctx.fillStyle= "#b0c2f7"; //ctx.fillStyle = "rgba(255, 255, 255, 0.05)"; ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h); } init(); } </script>
<div id="canvasDiv"> <canvas id="drawing" width="580px" height="788px" style="border:2px solid #000; background: #FFF;"></canvas> </div> <script> var canvas = document.getElementById('drawing'); var context = canvas.getContext('2d'); var imageObj = new Image();
imageObj.onload = function() { context.drawImage(imageObj, 69, 50); }; imageObj.src = 'http://localhost/test/Images/DSC0273446.jpg'; </script>
<div id="rect"> <p><button onclick="rect();">Rectangle</button></p> </div>
真的很感謝所有幫助,我可以在這個問題上得到,謝謝!