最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert small part of a canvas to png - Stack Overflow

programmeradmin0浏览0评论

I turning my html5 canvas into a png using the following code:

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

What do I add to this so it will only grab the top left 150x100 pixels, instead of the whole canvas?

I turning my html5 canvas into a png using the following code:

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

What do I add to this so it will only grab the top left 150x100 pixels, instead of the whole canvas?

Share Improve this question asked Jun 6, 2013 at 23:59 Matt CoadyMatt Coady 3,8667 gold badges43 silver badges64 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Create a second canvas of 150x100 pixels, grab the top left corner of the current canvas and paint it in with drawImage(), then call toDataURL() on the new canvas:

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+'"/>');

The way to do this would be to use another canvas element to get the area you want and then crop that.

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();

For anyone wanting to take any subsection of an initial canvas and convert it to png, the following modification of the code of @robertc worked for me:

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 cropStartY = 0;
saveCanvas.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+'"/>');
发布评论

评论列表(0)

  1. 暂无评论