我在下面有这个代码来向画布添加一个矩形,我对此有一些疑问。
- 创建后是否可以移动添加的矩形?
- 是否可以删除已添加的矩形?
在我添加了一堆矩形之后,我可以通过单击一个按钮来检索所有添加的矩形位置(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>
非常感谢我在这件事上能得到的所有帮助,谢谢!