使用javascript中的mousemove事件在canvas内的图像上绘制一个矩形
我试图在使用mousemove事件的canvas内的图像上绘制一个矩形。 但由于clearRect,我在图像上得到矩形,颜色填充在矩形中。 任何人都可以把我搞清楚 如何在图像上绘制一个只有边框的矩形。 下面是我实现它的代码。
var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), rect = {}, drag = false; function init() { var imageObj = new Image(); imageObj.onload = function() { ctx.drawImage(imageObj, 0, 0); }; imageObj.src = 'http://sofzh.miximages.com/javascript/darth-vader.jpg'; 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(rect.startX, rect.startY,rect.w,rect.h); draw(); } } function draw() { ctx.clearRect(rect.startX, rect.startY, rect.w, rect.h); ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h); }
Draw a rectangle!
您可能需要先使用clearRect
清除整个canvas,然后立即绘制imageObj
,最后绘制笔画。 所有这些都发生在mouseMove
函数内部,因此它基本上不断地连续绘制这些元素。
试试下面这个代码段:
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var rect = {}; var drag = false; var imageObj = null; function init() { imageObj = new Image(); imageObj.onload = function () { ctx.drawImage(imageObj, 0, 0); }; imageObj.src = 'http://sofzh.miximages.com/javascript/darth-vader.jpg'; 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) { ctx.clearRect(0, 0, 500, 500); ctx.drawImage(imageObj, 0, 0); rect.w = (e.pageX - this.offsetLeft) - rect.startX; rect.h = (e.pageY - this.offsetTop) - rect.startY; ctx.strokeStyle = 'red'; ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h); } } // init();