Html的Canvas主要通过js脚本做一些图形化操作。Canvas是一个矩形区域,您可以控制其每一像素。canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
如果有个需求,我们只想要用户相册图片中某个区域的内容,其余区域设为透明?
实现
- 先改变图片的大小
使用一个开源的canvas库pica。
// Resize from Canvas/Image to another Canvas
pica.resize(from, to, {
unsharpAmount: 80,
unsharpRadius: 0.6,
unsharpThreshold: 2
})
.then(result => console.log('resize done!'));
![img_82aa2f6339a31076c89bd8661e36dd08.png](https://yqfile.alicdn.com/img_82aa2f6339a31076c89bd8661e36dd08.png?x-oss-process=image/resize,w_1400/format,webp)
测试效果
- 实现图片的蒙版
图片蒙版主要是图片的叠加模式进行处理,参考以下链接
图片组合类型
ctx.save();
ctx.drawImage(mask_img, 0, 0);
ctx.globalCompositeOperation = "source-in";
ctx.drawImage(our_img, 0, 0);
ctx.restore();
![img_4bbe67ea83c792b1d20d4b1d7a76faa9.png](https://yqfile.alicdn.com/img_4bbe67ea83c792b1d20d4b1d7a76faa9.png?x-oss-process=image/resize,w_1400/format,webp)
mask.png
![img_7628d44a644a59d6e9d9d1f84ff6f636.png](https://yqfile.alicdn.com/img_7628d44a644a59d6e9d9d1f84ff6f636.png?x-oss-process=image/resize,w_1400/format,webp)
our_img
![img_f4f1eb1ce8bc55fe40e34e2f3462b5af.png](https://yqfile.alicdn.com/img_f4f1eb1ce8bc55fe40e34e2f3462b5af.png?x-oss-process=image/resize,w_1400/format,webp)
蒙版效果图
- 关于如何生成gif图,使用gif.js库。
var gif = new GIF({
workers: 2,
quality: 10,
background: "#ffffff00",
transparent:"ff0000"
});
gif.addFrame(img1);
gif.addFrame(img2);
gif.on('finished', function(blob) {
// window.open(URL.createObjectURL(blob));
var url = URL.createObjectURL(blob);
document.getElementById("gif").setAttribute("src",url)
});
gif.render();
最后
这里主要介绍了一些前端对图片处理的操作。