html5 worker 案例(2) 照片转换实际效果

日期:2021-02-25 类型:科技新闻 

关键词:在线抠图,稿定抠图,在线抠图透明图片,可以抠图的软件,凡科制图

worker的js编码img.js

拷贝编码
编码以下:

onmessage = function(e) {
postMessage(filter(e.data))
};
function filter(imgd) {
var pix = imgd.pixels.data;
var xcord = imgd.x / 1000;
var ycord = imgd.y / 1000;
for ( var i = 0, n = pix.length; i < n; i += 4) {
var grayscale = pix[i] * xcord + pix[i + 1] * .59 + pix[i + 2] * .11;
pix[i] = grayscale; // red
pix[i + 1] = grayscale; // green
pix[i + 2] = grayscale; // blue
}
imgd['pixels'].data = pix;
return imgd;
}

html编码

拷贝编码
编码以下:

<!DOCTYPE html>
<html>
<head>
<title>test2.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF⑻">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="../js/jquery⑴.8.0.min.js"></script>
</head>
<body>
<canvas id="myCanvas" width="640" height="480"></canvas>
<img src="../image/psu[4].jpg" class="onHover"> //留意,自身在这里插进1张照片,不然没用实际效果
<script type="text/javascript">
function process(img,x,y){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var pixels = context.getImageData(0,0,img.width,img.height);
var worker = new Worker("img.js");
var obj = {
pixels: pixels,
x:x,
y:y
}
worker.postMessage(obj);
worker.onmessage = function(e) {
if (typeof e.data === "string") {
console.log("Worker: " + e.data);
return;
}
var new_pixels = e.data.pixels; // Pixels from worker
context.putImageData(new_pixels, 0, 0);
img.src = canvas.toDataURL(); // And then to the img
}
}
</script>
<script type="text/javascript">
$(function(){
$(".onHover").on("mouseover", function(){
var x =this.width;
var y = this.height;
console.log("X: " + x + " Y: " + y);
process(this, x, y);
});
})
</script>
</body>
</html>

是实行上面的事例的情况下 ,要自身引进jquery包,而且在html网页页面上的img标识上放入自身要转换的照片。随后布署到服务器,开启网页页面,当电脑鼠标挪动到照片的 上面的情况下就会产生转换,在这里实行转换作用的涵数有worker负责,随便不危害网页页面自身的高效率,相近于java語言中的线程同步。