我已经举了这个例子来说明我的问题:http://jsfiddle.net/GSRgf/
HTML
<canvas id="canvas" width="500" height="500"></canvas>
<div id="div"></div>
JS
$(function() {
var ctx=$('#canvas')[0].getContext('2d');
rect = {};
drag = false;
$(document).on('mousedown','#canvas',function(e){
rect.startX = e.pageX - $(this).offset().left;
rect.startY = e.pageY - $(this).offset().top;
rect.w=0;
rect.h=0;
drag = true;
});
$(document).on('mouseup','#canvas',function(){
drag = false;
});
$(document).on('mousemove','#canvas',function(e){
if (drag) {
rect.w = (e.pageX - $(this).offset().left)- rect.startX;
rect.h = (e.pageY - $(this).offset().top)- rect.startY;
ctx.clearRect(0, 0, 500, 500);
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
});
});
当鼠标悬停在div上时,如何继续绘制矩形?
谢谢!
答案 0 :(得分:1)
删除mousemove和mouseup事件的“#canvas”选择器。 编辑mousemove事件以使用$(“#canvas”)而不是$(this)。
$(function() {
var ctx=$('#canvas')[0].getContext('2d');
rect = {};
drag = false;
$(document).on('mousedown','#canvas',function(e){
rect.startX = e.pageX - $(this).offset().left;
rect.startY = e.pageY - $(this).offset().top;
rect.w=0;
rect.h=0;
drag = true;
});
$(document).on('mouseup',function(){
drag = false;
});
$(document).on('mousemove',function(e){
if (drag) {
rect.w = (e.pageX - $("#canvas").offset().left)- rect.startX;
rect.h = (e.pageY - $("#canvas").offset().top)- rect.startY;
ctx.clearRect(0, 0, 500, 500);
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
});
});