Sim*_*amp 31 html5 google-chrome clip html5-canvas
我在画布上使用了clip()函数.
结果:

正如你所看到的那样,镀铬版本沿着边缘有可怕的锯齿/锯齿.我该如何解决?
代码重现:
<canvas id="test" width="300" height="300"></canvas>?
<script type="text/javascript">
cv = document.getElementById("test");
ctx = cv.getContext("2d");
var im = new Image();
im.onload = function () {
ctx.beginPath();
ctx.arc(110, 110, 100, 0, 2*Math.PI, true);
ctx.clip();
ctx.drawImage(im, 0, 0);
}
im.src = "http://placekitten.com/300/300";
</script>
Run Code Online (Sandbox Code Playgroud)
Dan*_*sky 25
如果您正在执行复杂的分层绘图,则可以使用globalCompositeOperation在第二个临时画布中模拟剪裁.然后,您可以使用drawImage将临时画布复制回原始画布.我不能保证这种方法的表现,但这是我知道得到你想要的唯一方法.
//set-up - probably only needs to be done once
var scratchCanvas = document.createElement('canvas');
scratchCanvas.width = 100;
scratchCanvas.height = 100;
var scratchCtx = scratchCanvas.getContext('2d');
//drawing code
scratchCtx.clearRect(0, 0, scratchCanvas.width, scratchCanvas.height);
scratchCtx.globalCompositeOperation = 'source-over'; //default
//Do whatever drawing you want. In your case, draw your image.
scratchCtx.drawImage(imageToCrop, ...);
//As long as we can represent our clipping region as a single path,
//we can perform our clipping by using a non-default composite operation.
//You can think of destination-in as "write alpha". It will not touch
//the color channel of the canvas, but will replace the alpha channel.
//(Actually, it will multiply the already drawn alpha with the alpha
//currently being drawn - meaning that things look good where two anti-
//aliased pixels overlap.)
//
//If you can't represent the clipping region as a single path, you can
//always draw your clip shape into yet another scratch canvas.
scratchCtx.fillStyle = '#fff'; //color doesn't matter, but we want full opacity
scratchCtx.globalCompositeOperation = 'destination-in';
scratchCtx.beginPath();
scratchCtx.arc(50, 50, 50, 0, 2 * Math.PI, true);
scratchCtx.closePath();
scratchCtx.fill();
//Now that we have a nice, cropped image, we can draw it in our
//actual canvas. We can even draw it over top existing pixels, and
//everything will look great!
ctx.drawImage(scratchCanvas, ...);
Run Code Online (Sandbox Code Playgroud)
我们在临时画布中执行此操作的原因是,destination-in是一种非常具有破坏性的操作.如果你已经在主画布中绘制了一些东西(也许你在背景中放下了一个漂亮的渐变),然后想要绘制一个剪裁的图像,那么剪裁圆圈也会剪掉你已绘制的所有内容.当然,如果您的特定情况更简单(也许您想要绘制的是剪切图像),那么您可以放弃刮刮画布.
您可以在我的演示页面上使用不同的剪辑模式.底行(带有渐变)对你来说不是很有用,但是顶行(带圆圈和正方形)更相关.
编辑
哎呀,我不小心分叉你的JSFiddle来演示这个技术.
小智 5
我在Chrome和clip()中遇到了同样的问题.
在我的情况下,我通过设置canvas globalCompositeOperation实现了更好的浏览器兼容性.
context.globalCompositeOperation = 'source-atop';
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下画出你的形状,一个圆圈.然后切换到'source-atop'并绘制你的小猫图像.
请注意,这是基本绘图的快速修复,并假设为空白画布.以前的画布绘图会影响剪辑.
| 归档时间: |
|
| 查看次数: |
9678 次 |
| 最近记录: |