将画布的一小部分转换为png

时间:2013-06-06 23:59:01

标签: javascript html5 canvas

我使用以下代码将html5画布转换为png:

var canvas = document.getElementById("mycanvas");
var img    = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');

我添加了什么,所以它只会抓住左上角的1​​50x100像素,而不是整个画布?

3 个答案:

答案 0 :(得分:5)

创建一个150x100像素的第二个画布,抓住当前画布的左上角并使用drawImage()绘制它,然后在新画布上调用toDataURL()

var canvas = document.getElementById("mycanvas");
var new_canvas = document.createElement('canvas');
new_canvas.width = 150;
new_canvas.height = 100;
new_canvas..getContext('2d').drawImage(canvas, 150, 100);
var img = new_canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');

答案 1 :(得分:2)

执行此操作的方法是使用另一个canvas元素来获取所需的区域,然后裁剪它。

var canvas      = document.getElementById('mycanvas'),
    smallcanvas = document.createElement('canvas'),
    imagedata   = '';

smallcanvas.getContext('2d').drawImage(canvas, 0, 0, null, null, 0, 0, 150, 100);
imagedata = smallcanvas.toDataURL();

答案 2 :(得分:0)

对于希望将初始画布的任何子部分转换为png的任何人,@ robertc代码的以下修改对我来说都是有效的:

let canvas = document.getElementById("mycanvas");
let saveCanvas = document.createElement('canvas');
saveCanvas.width = 150; // width of saved image
saveCanvas.height = 100; // height of saved image
let cropStartX = 0; // position to start cropping image
let cropStartX = 0;
new_canvas.getContext('2d').drawImage(canvas, cropStartX, cropStartY, saveCanvas.width, saveCanvas.height, 0, 0, saveCanvas.width, saveCanvas.height);
var img = new_canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');