简体   繁体   English

画布到多个图像

[英]Canvas to Multiple Images

I've created a canvas of size 1240x3500 . 我创建了一个大小为1240x3500的画布。

I need to convert it to a pair of images., ie, from (0,0) to (1240,1750) and from (0,1751) to (1240,3500) . 我需要将其转换为一对图像,即,从(0,0)(1240,1750)和从(0,1751)(1240,3500)

Is is possible to achieve this using toDataURL() or is there any other function to establish this? 是否可以使用toDataURL()实现此toDataURL()或者是否有其他函数可以建立此目的?

There is not such a method available out of the box. 开箱即用没有这种方法。 Good news is that it's quite simple to make: 好消息是制作起来非常简单:

  • create a new (off-screen) canvas the size of the region 创建区域大小的新(屏外)画布
  • clip-draw the part of the original image into the new canvas 将原始图像的一部分剪贴到新画布中
  • call toDataURL() on the new canvas 在新画布上调用toDataURL()

One way: 单程:

function regionToUri(canvas, x, y, w, h) {

    var ncanvas = document.createElement('canvas'), // create new canvas
        ctx = ncanvas.getContext('2d');

    ncanvas.width = w;                              // set it to target size
    ncanvas.height = h;

    ctx.drawImage(canvas, x, y, w, h, 0, 0, w, h);  // use region draw

    return ncanvas.toDataURL();                     // return data-uri
}

Modify the return statement if you need another format than PNG (or better, supply a parameter for this as well). 如果您需要除PNG之外的其他格式(或更好地为此提供一个参数),请修改return语句。

var dataURI = regionToUri(originalCanvas, x, y, w, h);

Note: For this to work your original image must fulfill CORS requirements. 注意:要使此功能生效,您的原始图像必须满足CORS要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM