How to realize the effect of picture transformation in html5 worker
Today, I will talk to you about how to achieve the effect of picture transformation in html5 worker, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Js code img.js for worker
The code is as follows:
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代码 代码如下: test2.html
/ / Note: insert a picture here by yourself, otherwise it will be useless
Function process (img,x,y) {
Var canvas = document.getElementById ("myCanvas")
Var context = canvas.getContext ('2d')
Context.drawImage (img, 0,0)
Var pixels = context.getImageData (0re0dir img.widthjimg.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
}
}
$(function () {)
$(".onHover") .on ("mouseover", function () {
Var x = this.width
Var y = this.height
Console.log ("X:" + x + "Y:" + y)
Process (this, x, y)
});
})
When executing the above example, introduce the jquery package yourself and put the image you want to change on the img tag on the html page. Then deploy to the server, open the page, when the mouse moves over the picture, it will change, where the function to perform the transformation function is responsible for worker, at will does not affect the efficiency of the page itself, similar to the multi-thread in the java language.
After reading the above, do you have any further understanding of how to achieve the effect of picture transformation in html5 worker? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.