将画布的一部分复制到图像 [英] Copy a part of canvas to image

查看:52
本文介绍了将画布的一部分复制到图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试复制画布的某个部分,然后将复制的部分写到图像中.这是我的(错误的)方法:

I try to copy a certain part of a canvas, then write the copied part in an image. Here is my (wrong) approach:

var c = document.getElementById('MyCanvas'),
ctx = c.getContext('2d');
var ImageData = ctx.getImageData( 25, 25, 150, 150 );

var MyImage = new Image();
MyImage.src = ImageData ; //   <-- This is wrong, but I mean something like this

您知道我该怎么办吗?预先谢谢你.

Do you know how can I do it? Thank you in advance.

ps:我不想复制整个画布,但是要复制其中的某个部分.

ps: I don't want to copy the whole canvas, but a certain part of it.

推荐答案

您可以通过以下方式完成此任务...

You could accomplish that in the following way ...

var c = document.getElementById('MyCanvas');
var ctx = c.getContext('2d');

// draw rectangle
ctx.fillRect(0, 0, 200, 200);
ctx.fillStyle = '#07C';
ctx.fillRect(25, 25, 150, 150);

// get image data
var ImageData = ctx.getImageData(25, 25, 150, 150);

// create image element
var MyImage = new Image();
MyImage.src = getImageURL(ImageData, 150, 150);

// append image element to body
document.body.appendChild(MyImage);

function getImageURL(imgData, width, height) {
   var canvas = document.createElement('canvas');
   var ctx = canvas.getContext('2d');
   canvas.width = width;
   canvas.height = height;
   ctx.putImageData(imgData, 0, 0);
   return canvas.toDataURL(); //image URL
}

<canvas id="MyCanvas" width="200" height="200"></canvas>

道歉没有给出解释

这篇关于将画布的一部分复制到图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆