Copying canvas via toDataURL after draw operation does not work
I'm trying to copy the contents of one canvas to another with this code:
generateThumbnail: function(i) {
var thumbnailImage = new Image();
thumbnailImage.src = $("canvas")[i].toDataURL();
var thumbnailCanvas = $("#thumbnail")[0];
var ctx = thumbnailCanvas.getContext("2d");
ctx.drawImage(thumbnailImage, 0, 0);
}
It works, but not if I've just completed a drawing operation (e.g. line fill). If I've just completed a draw operation, it does nothing upon first execution, but if I call it a second time it works. This seems pretty strange, and I'm unsure why this is happening.
It's as if the canvas is in some kind of invalid state where it can't be read from or something.
The code that is drawing the line is here:
eraseLine: function(o) {
var c 开发者_如何学Go= this.context;
var lineWidth = o.radius * 2;
// Stroke Line
if (this.stroke) {
c.lineWidth = lineWidth + 4;
c.globalCompositeOperation = 'source-atop';
c.strokeStyle = this.strokeColor;
c.beginPath();
c.moveTo(o.x0, o.y0);
c.lineTo(o.x1, o.y1);
c.stroke();
}
// Erase Line
c.lineWidth = lineWidth;
c.lineCap = 'round';
c.strokeStyle = 'rgba(255, 255, 255, 1)';
c.globalCompositeOperation = 'destination-out';
c.beginPath();
c.moveTo(o.x0, o.y0);
c.lineTo(o.x1, o.y1);
c.stroke();
c.globalCompositeOperation = 'source-over';
}
I've tested this on Chrome 11 and Firefox 5, and it happens on both. Any ideas why this is happening?
Can you try this?
generateThumbnail: function(i) {
var thumbnailImage = new Image();
thumbnailImage.onload = function() {
var thumbnailCanvas = $("#thumbnail")[0];
var ctx = thumbnailCanvas.getContext("2d");
ctx.drawImage(thumbnailImage, 0, 0);
}
thumbnailImage.src = $("canvas")[i].toDataURL();
}
It seems as if the loading of this image takes longer after you performed a drawing operation. So the image is not loaded when you execute the drawImage
command. The second time you call this function the image seems to load faster. Anyway, you should always use the onload event when you are loading an image.
精彩评论