canvas把图片变黑白并保存

2 篇文章 0 订阅
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
html,body{
width:100%;
height:100%;
}
</style>
</head>
<body>
<div id="canvas" style="width:500px;height:500px;position:relative;margin:0 auto;"></div>
</body>
</html>
<script>
var jquery = (function($){
var $ = function(id){
return document.getElementById(id) || id;
}
return $;
}());


var color = (function($){
var extend = function(target,source){
for(var x in source){
if(x in target){
target[x] = source[x];
}
}
return target;
}


var addEvent = function(obj,event,func){
obj.addEventListenter ? obj.addEventListenter(event,func) : obj.attachEvent("on"+event,function(){func.call(obj)});
}


window.requestAnimation = function(){
return  window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(fn){
return window.setTimeout(fn,1000/60);
}
}

/**
         * 获取mimeType
         * @param  {String} type the old mime-type
         * @return the new mime-type
         */
        var _fixType = function(type) {  //获取图片的mime类型
            type = type.toLowerCase().replace(/jpg/i, 'jpeg');
            var r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image/' + r;
        };


/**
         * 在本地进行文件保存
         * @param  {String} data     要保存到本地的图片base64数据
         * @param  {String} filename 文件名
         */
        var saveFile = function(data, filename){
            var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = data;
            save_link.download = filename;
           
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            save_link.dispatchEvent(event);
        };


var init = function(opt){
this.option = {
element : null
}


extend(this.option,opt);
this.initialize();
}


init.prototype = {
initialize : function(){
this.canvas = this.createCanvas();
this.ctx = this.canvas.getContext("2d");
this.turnColor();
},


turnColor : function(){
var image = new Image(),_this = this;
image.src = "./1.jpg";
image.onload = function(){
$(_this.option.element).style.width = parseInt(image.width)+"px";
                    $(_this.option.element).style.height = parseInt(image.height)+"px";
_this.canvas.width = parseInt(image.width);
_this.canvas.height = parseInt(image.height);
_this.ctx.drawImage(image,0,0);
var imageData = _this.ctx.getImageData(0,0,image.width,image.height);


for(var i = 0,imageDataLeng = imageData.data.length;i < imageDataLeng;i += 4){
// First bytes are red bytes.        
// Get red value.
var myRed = imageData.data[i];


// Second bytes are green bytes.
// Get green value.
var myGreen = imageData.data[i + 1];


// Third bytes are blue bytes.
// Get blue value.
var myBlue = imageData.data[i + 2];


// Fourth bytes are alpha bytes
// We don't care about alpha here.
// Add the three values and divide by three.
// Make it an integer.
myGray = parseInt((myRed + myGreen + myBlue) / 3);


// Assign average to red, green, and blue.
imageData.data[i] = myGray;
imageData.data[i + 1] = myGray;
imageData.data[i + 2] = myGray;


}
_this.ctx.putImageData(imageData,0,0);


// 图片导出为 png 格式
var type = 'png';
var imgData = _this.canvas.toDataURL(type);  //获取canvas的图片base64数据


// 加工image data,替换mime type
imgData = imgData.replace(_fixType(type),'image/octet-stream');


// 下载后的问题名
var filename = '1.' + type;
// download
saveFile(imgData,filename);
}
},


createCanvas : function(){
var canvas = document.createElement("CANVAS");
canvas.innerHTML = "canvas";
canvas.width = parseInt($(this.option.element).style.width);
canvas.height = parseInt($(this.option.element).style.height);
$(this.option.element).appendChild(canvas);
return canvas;
}
}


return init;
}(jquery || {}));


window.onload = function(){
var option = {
element : "canvas"
}
new color(option);
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Vue3 中,可以使用以下步骤利用 Canvas 裁剪图片保存: 1. 在 Vue3 中,可以使用 `ref` 或 `setup()` 中的 `refs` 来获取 `<canvas>` 元素的引用。 ```html <template> <div> <canvas ref="canvas"></canvas> <input type="file" accept="image/*" @change="onFileChange"> <button @click="cropImage">Crop Image</button> </div> </template> ``` ```javascript import { ref } from 'vue'; export default { setup() { const canvasRef = ref(null); return { canvasRef, }; }, }; ``` 2. 在 `onFileChange` 方法中获取上传的图片,并将其绘制到 `<canvas>` 中。 ```javascript async function onFileChange(event) { const file = event.target.files[0]; const image = new Image(); image.onload = () => { canvasRef.value.width = image.width; canvasRef.value.height = image.height; const context = canvasRef.value.getContext('2d'); context.drawImage(image, 0, 0); }; image.src = URL.createObjectURL(file); } ``` 3. 在 `cropImage` 方法中获取裁剪后的图片,并将其保存。 ```javascript async function cropImage() { const context = canvasRef.value.getContext('2d'); const imageData = context.getImageData(0, 0, canvasRef.value.width, canvasRef.value.height); const data = imageData.data; // 获取裁剪后的图片数据 const croppedImageData = context.getImageData(x, y, width, height); const croppedData = croppedImageData.data; // 将裁剪后的图片绘制到新的 Canvas 中 const newCanvas = document.createElement('canvas'); newCanvas.width = width; newCanvas.height = height; const newContext = newCanvas.getContext('2d'); newContext.putImageData(croppedImageData, 0, 0); // 将新的 Canvas 转换为图片,并保存 const newImage = new Image(); newImage.src = newCanvas.toDataURL('image/png'); document.body.appendChild(newImage); } ``` 在以上代码中,`x`、`y`、`width`、`height` 分别表示裁剪区域的左上角坐标和宽高。裁剪后的图片数据可以使用 `getImageData()` 方法获取,然后再将其绘制到新的 Canvas 中,最后将新的 Canvas 转换为图片,并保存
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值