画布绘图不起作用

时间:2011-12-30 14:52:55

标签: jquery html5 canvas

在我正在处理的应用程序中,应该可以打开几个div框并在每个div框上绘制(如MS绘制灯光)。

我已经成功打开一个盒子然后画上它但是当我从画布“id”改为画布“class”时(为了能够打开几个盒子并在每个盒子上画画)它停止了工作。现在,当我尝试绘画时,没有任何反应。我做错了什么?

var color = "red";
var shape = "square";
var size = 10;

var theWindow = $('.window').last();
var bottomWindow = $('.windowBottom').last();

var letsdraw = false;
var theCanvas = $('.paint').last();

var ctx = theCanvas.getContext('2d');
ctx.strokeStyle = 'red';
theCanvas.width  = 430;
theCanvas.height = 317;

var canvasOffset = $(theCanvas).offset();

$(theCanvas).mousemove(function(e) {
    if (letsdraw === true) {
        ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
        ctx.stroke();
    }
});

$(theCanvas).mousedown(function(e) {
    letsdraw = true;
    ctx.strokeStyle = color;
    ctx.lineWidth = size;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
});

$(window).mouseup(function() {
    letsdraw = false;
});

1 个答案:

答案 0 :(得分:2)

这个问题是你仍然将它视为一个画布。

$('.paint').mousemove(function(e) {
    if (letsdraw === true) {
        var ctx = this.getContext('2d');
        var canvasOffset = $(this).offset();
        ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
        ctx.stroke();
    }
});

所以我删除了theCanvas并使用this来引用画布。单击演示链接以查看其实际操作:

Demo

<小时/> 使用data attr进行了一些编辑:

// using data attr to store lets draw per canvas
$(window).mouseup(function() {
    $('.paint').each(function () {
       $(this).data('letsdraw', false); 
    });
});

$('.paint').mousemove(function(e) {
    if ($(this).data('letsdraw') === true) {
        var ctx = this.getContext('2d');
        var canvasOffset = $(this).offset();
        ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
        ctx.stroke();
    }
});

更改高度和宽度:

$('.paint').each(function () {
    this.width = 430;
    this.height = 20
})

我只执行一次,因为更改画布的高度/宽度实际上会删除所有绘图。

相关问题