HTML Canvas剪辑和putImageData [英] HTML Canvas clip and putImageData

查看:512
本文介绍了HTML Canvas剪辑和putImageData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在背景中有一个大图像的画布,在它前面有一个较小的圆形图像。我通过使用剪辑像这样实现这个圆形图像效果

I have a canvas with a large image in the background and a smaller round image in front of it. I achieved this round image effect by using clip like so

ctx.save();

ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2, true);   
ctx.closePath();
ctx.clip();

ctx.drawImage(img,x-r,y-r,2*r,2*r);     // draw the image
ctx.restore();

然后我想旋转圆形图像,所以我使用第二个上下文和旋转和重绘

then I want to rotate the round image, so I use a second context and rotate and redraw like so

backCanvas=document.createElement('canvas');    
backContext=backCanvas.getContext('2d');
backCanvas.width=w;
backCanvas.height=h;

backContext.translate(w/2,h/2);
backContext.rotate(a);

backContext.drawImage(img,-w/2,-h/2,w,h);

var imgData=backContext.getImageData(0,0,w,h);

ctx.save();

ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2, true);   
ctx.closePath();
ctx.clip();
ctx.putImageData(imgData,x,y);

ctx.restore();

但是会发生什么是黑色透明的背景从背面画布复制,

But what happens is that the black-transparent background gets copied from the back canvas and the clip fails to "clip" it.

任何帮助将不胜感激。

推荐答案

根据 specs


当前路径,变换矩阵,阴影属性,全局alpha, / strong>,并且全局组合运算符不能影响getImageData()和putImageData()方法。

The current path, transformation matrix, shadow attributes, global alpha, the clipping region, and global composition operator must not affect the getImageData() and putImageData() methods.

在你的情况下,为什么要使用额外的画布和像素数据操作?为什么不只是

In your case, why are you using an additional canvas and pixel data manipulations? Why not just

ctx.save();

ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);   
ctx.closePath();
ctx.clip();

ctx.translate(x, y);
ctx.drawImage(img, -r, -r, 2*r, 2*r);
// not restoring context here, saving the clipping region and translation matrix

// ... here goes the second part, wherever it is:
ctx.save();
ctx.rotate(a);
ctx.drawImage(img, -r, -r, 2*r, 2*r);
ctx.restore();

这篇关于HTML Canvas剪辑和putImageData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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